9

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))
ThierryMichel
  • 327
  • 1
  • 4
  • 16
  • These two question might help you https://stackoverflow.com/questions/45373742/detect-route-change-with-react-router/45373907#45373907 and https://stackoverflow.com/questions/32841757/detecting-user-leaving-page/45869459#45869459 – Shubham Khatri Feb 28 '18 at 05:31
  • Thank you @Shubham Kathri but the following link was a bit more helpful: [link](https://stackoverflow.com/questions/39342195/intercept-handle-browsers-back-button-in-react-router) – ThierryMichel Mar 05 '18 at 04:54

1 Answers1

24

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...
  }
}
Community
  • 1
  • 1
Viraj
  • 410
  • 5
  • 10
  • 4
    how can you then prevent the default back button behaviour and use your own? – dan674 Aug 05 '18 at 23:27
  • @dan674 it has been a little while but i do not think that there is a default behavior. What was happening in may case was that the api call was getting triggered in componentDidMount lifecycle hook. By detecting that the back button had been pressed, i was able to make the api call conditional. Hope this helps. You can see the code here [link](https://github.com/thierryMic/redeable/blob/master/frontend/src/containers/CategoryContainer.js) – ThierryMichel Aug 23 '18 at 06:30
  • how to differentiate between forward and back button? Your above code triggers both forward and back. – Ali Rehman Oct 14 '20 at 11:04