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))
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...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With