Home > Software engineering >  React Router: change URL path on goBack()
React Router: change URL path on goBack()

Time:09-30

There's a blog post on /post/public/:postId which is public. On this same page there is the edit button which goes to /edit/:postId page where user can change the post privacy from public to private.

After changing the post from public to private the previous URL /post/public/:postId becomes invalid and the new url is /post/private/:postId where we can see this post.

But on Edit page, after changing the privacy (which changes the post URL), click on Cancel button this.props.history.goBack() navigates back to public URL which is now invalid, hence results 404.

Is there a way I can update the goBack() url depending on if user changes privacy? I wish to navigate the users to the updated URL when privacy changes from public to private and vice versa.

P.s.: this.props.history.push() or this.props.history.replace() can temporarily fix the issue, but if the user will click on browser's default back button it will still go back to the invalid page.

Thanks!

CodePudding user response:

    const [ locationKeys, setLocationKeys ] = useState([])
    const history = useHistory()

    useEffect(() => {
     return history.listen(location => {
      if (history.action === 'PUSH') {
       setLocationKeys([ location.key ])
      }

      if (history.action === 'POP') {
      if (locationKeys[1] === location.key) {
        setLocationKeys(([ _, ...keys ]) => keys)

        // Handle forward event

      } else {
        setLocationKeys((keys) => [ location.key, ...keys ])

        // Handle back event

      }
    }
  })}, [ locationKeys, ])

This may help you!

CodePudding user response:

I think this is more a logical issue. When the user is on the public post page and navigates to edit the post, do a redirect here to the edit path.

  • A -> "/post/public/:postId" -> "edit" -> replace("/edit/:postId")
  • A -> "/edit/:postId"

They can now toggle the public/private mode of the post, and if/when they do a back navigation the will go back to the page they were on previously, i.e. A above.

  • A -> "/edit/:postId" -> "cancel" -> goBack()
  • A

If the user completes and, presumably, saves (or commit) the edit, then again, redirect to the correct private/public path.

  • A -> "/edit/:postId" -> "save" -> replace("/post/private/:postId")
  • A -> "/post/private/:postId"

The idea here is to keep the history stack valid by not keeping potentially "stale" paths in the history.

  • Related