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...
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))
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...
}
}