Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 287
ThierryMichel Avatar asked Feb 28 '18 05:02

ThierryMichel


1 Answers

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...
  }
}
like image 145
Viraj Avatar answered Sep 21 '22 16:09

Viraj