Search code examples
reactjshtml5-history

In React, can I check where the user will go with history.goBack()


I'm using react-query and I want to send the user back to the previous page when they save a form that triggers a query invalidation-- except in the case in which going back will send the user to the current page (the user's history started on that page), as this causes an infinite loop.

Here's my code:

  const history = useHistory();
  const mutatePost = useMutation(
    (jsonData : InterfaceJsonData) => fetchPostWithUserAuth(
      postUrl(id), fetchOptionsPost(jsonData, id),
    ), {
      onSuccess: () => {
        history.goBack();

How can I check where history.goBack() goes? In the rare case that the user started on the current page, I don't want to accidentally create an infinite loop.

I'm using history.goBack() because the component is used in three places, and I want to redirect to the relevant page (one of three pages). If there is some way to search the history to check which of the three previous pages was visited, that would be perfect.


Solution

  • You can build a history stack when the user arrives at your site, you push into an array every single page, where the user navigated. Then if the user pushes the back button, you know what's happening. If the array is empty, you know, this was the first page. Or another solution might be this.