1
votes

I'm starting to learn react router, and I'm having some issues, with using the goBack function, which is inside the history property in React Router.

I have a simple route, where I render a dummy post, form the JsonPlaceHolder API, and make a button to go back, which executes this function.

   returnToForwardPageHandler = () =>{
    this.props.history.goBack(); 
}

now the post is loaded dynamically, depending on the ID, which is given.

 componentDidMount () {
    if(this.props.match.params.id){
        if ( !this.state.loadedPost || (this.state.loadedPost && this.state.loadedPost.id !== this.props.id) ) {
            axios.get( 'https://jsonplaceholder.typicode.com/posts/' + this.props.match.params.id)
                .then( response => {
                    // console.log(response);
                    this.setState( { loadedPost: response.data 
                } );
                } );
            }
        }
    }

but I do get a different result depending on how the id is given.

In my component, where the id is sat, of the given post

  postSelectedHandler = (id) => {
    //this.setState({selectedPostId: id});
    this.props.history.push('/' + id)
}

it works fine if I set the state manually of the id. But I have to click the button (execute the returnToForwardPageHandler function) twice if I use this.props.history.push('/' + id), shouldn't the outcome be the same, what am I missing?

1

1 Answers

2
votes

I hope this helps. if not please provide the information regarding your routes.

postSelectedHandler = (id) => {
    //this.setState({selectedPostId: id});
    this.props.history.push(`/${id}`)
}