Search code examples
javascriptreactjsstatepersistencereload

Persist state after reload in react


Once I go to a particular page by passing in props to that page I want to be able to reload the page without losing the state, currently, when I reload, the page throws an error, that the prop is missing. For example if I use

history.push({ pathname: '/animal-details',animal_id: animal.id }) it shows the details on these next page but when I reload the page the data goes away and the page is left blank. How to get around this? Thank You.


Solution

  • Aside from using localStorage or cookies, I think this is a good situation to just make the animal_id part of the path.

    Instead of doing

    history.push({ pathname: '/animal-details',animal_id: animal.id })
    

    I would do:

    history.push(`/animal-details/${animal.id}`)
    

    using a template literal.

    If you're using react-router-dom, you can get the animal id using the location prop or the useLocation hook.

    const path = props.location.pathname.split('/')
    const animalId = path[path.length - 1] // the animal id is the last value in the array
    

    If you aren't using react-router-dom for whatever reason, you can also do something similar using vanilla js window.location.href.