Detecting That the Back Button Was Pressed in React-Router

I have this component that retrieves posts from an api but everytime the user presses the back button, the componentDidMount event is triggered and the api call is repeated.

Does react or react-router provide a way to detect that the back-button was pressed so i can prevent the api call?

import React, { Component } from 'react'
import { fetchData } from '../actions/actions'
import { connect } from 'react-redux'
import { receivePosts } from '../actions/actions'
import { PostList } from '../components/PostList'
import { withRouter } from 'react-router-dom'

class PostListContainer extends Component {


componentDidMount() {            
        this.props.fetchData("posts", receivePosts)
}


render() {
    const { posts, active} = this.props
    return (
        <PostList
            posts={active === '' ? posts : posts.filter( p => p.category === active)}
        />
    )}
}


function mapStateToProps (state) {
    return {
        posts:state.posts,
        active:state.categories.activeFilter
    }
}

function mapDispatchToProps(dispatch)  {
    return {
        receivePosts: () => dispatch(receivePosts()),
        fetchData: (e, h) => dispatch(fetchData(e, h))
    }
}


export default withRouter(connect(mapStateToProps, mapDispatchToProps)(PostListContainer))
2

1 Answer

to detect the back button in the browser you can use window.onpopstate event, use that in componentDidUpdate like this, this worked for me.

componentDidUpdate(){    
  window.onpopstate = e => {
     //your code...
  }
}
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest