Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react router is only replacing the final route on history.push

I am trying to redirect with react router to another page after a certain amount of time has passed.

The code I have so far is:

 submitActivity(){
        axios.post('/tiles', {
            activityDate:this.state.startDate,
            planId:this.state.planId,
            value:this.state.sliderValue
        })
            .then(res=>{
                console.log(res);
                this.modalHandleShow();
                setTimeout(function(){
                    this.goBackToTile();
                }.bind(this),3000);
            })
            .catch(err=>console.log(err));
    }

    goBackToTile(){
        this.props.history.push(`tile/${this.state.tileId}`)
    }

history is definitely being called, but the url which is currently

/addActivity/tile/2/plan/9

only gets changed to /addActivity/tile/2/plan/tile/2

while /tile/2 is correct I don't understand why the rest of the url stays in tact?

like image 466
KAT Avatar asked Jul 10 '18 23:07

KAT


People also ask

What is the difference between history push and history replace?

replace and history. push? The difference is that, in case of push - a new record is added in the history, while for replace it deletes the last record and puts the new one.

How do I get the previous route on my react router?

To detect previous path in React Router, we can set the state property to an object with the location. pathname as the value. <Link to={{ pathname: "/nextpath", state: { prevPath: location.

What is difference between push and replace in react router?

You can either push a new record onto the top of the history stack or you can replace the top record. If you use push , and then hit the browser's back button, it will take you back to the page you are currently on, but if you use replace it will take you two pages back.

Is useHistory deprecated?

The use of history and useHistory is deprecated and should be replaced with the useNavigate hook.


1 Answers

Make sure you include a / in the beginning of the string, or it will be used relative to your current url.

goBackToTile() {
    this.props.history.push(`/tile/${this.state.tileId}`)
}
like image 70
Tholle Avatar answered Nov 14 '22 23:11

Tholle