2

I want to navigate backwards after clicking a submit button in a form for which I used history.goBack but in case there is no previous page/history, i want to navigate to a screen with thank you message using history.replace.

const handleSubmit = () => {
     history.goBack(); // will do nothing if there's no previous history
     // If no prev history
     history.replace({pathname: `${url}/submit`});
}

Now for the case where there is previous history, history.goBack would navigate to the previous page, but it being asynchronous and history.replace being synchronous, it navigates to the /submit page first and then history.goBack is executed. How do i await the execution of history.goBack?

Utkarsh Kumar
  • 71
  • 1
  • 6
  • Does this answer your question? [How to know if react-router can go back to display back button in react app](https://stackoverflow.com/questions/37385570/how-to-know-if-react-router-can-go-back-to-display-back-button-in-react-app) – ziishaned Sep 02 '21 at 11:29

3 Answers3

0
const handleSubmit = () => {
    if (history.length > 2) {
        // if history is not empty, go back:
        window.History.back();
    } else if (url) {
        // go to specified fallback url:
        window.History.replaceState(null, null, url);
    } else {
        // go home:
        window.History.replaceState(null, null, '/');
    }
}

try this one, this is from the answer in this post, How to check if the user can go back in browser history or not, but it's not always working.

IMO, your task can't be done, because there's no way to tell if there's previous history. Besides your previous history stored in the React has nothing to do with the Browser history, because a user could first visit google.com and then arrive to your site. So implementing this is not going to work at all. Not to mention React itself is a single URL application, this of course complicate things a bit.

windmaomao
  • 7,120
  • 2
  • 32
  • 36
0

You could try to check if the user was from another route:

By checking history action:

const handleSubmit = () => {
     if (history.action !== 'POP') {
        history.goBack();
     }
     history.replace({pathname: `${url}/submit`});
}

action === 'POP' means it's the initial load of your page, and it also works when the user was from an external URL

Ryan Le
  • 7,708
  • 1
  • 13
  • 23
0
history.goBack();

// Register a popstate listener that executes only once during the next history entry change
window.addEventListener('popstate', onPopStateCallback, {once: true});

Create a onPopStateCallback and you can do the replace within the callback

Ranjith Kumar
  • 681
  • 6
  • 7