how to pass props get persist using history.push

3k views Asked by At

i need to access data that are pass as a props from one component to another component by history.push,data becomes undefined when page reload,and i dont want to use redux so anyone have suggestion..Thankyou!

1

There are 1 answers

2
WebstraDev On

Your best bet is probably passing a state object in the history.push call.

 history.push({
           pathname: '/path',
           state: { key1: 'hello this is data needed in another component',  }
       });

this behaves the same way as

history.push('/path')

But adds a state object which you can access in the other component on the location object.

In the component you redirect to you will do something like

const data = location.state?.key1

I am using the ? there for cases where you use the component without being redirected, meaning the state would be null.

If you want your data to persist over reloads of the applications then consider using either the browsers localstorage, by setting an item in localstorage localStorage.setItem("key", "value") and then doing `localStorage.getItem("key") in the second component. This becomes messy when you have multiple components calling this as there will be duplicate calls to the same state key. In which case redux would be a better option.

Another option would be to use query parameters and adding the state in the URL, which has the added bonus of being able to send someone a link to your app with a certain state already set.