Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs save current state of component

Tags:

reactjs

I have Component A and Component B. In component A, users can apply filters to a list of elements and they navigate between the two components using a side bar. Whenever users click to go to B, and back to A, the filters are set back to the initial state. What is the best way to save the state of component A so that when they come back to it, they see all of the filters they originally applied.

like image 495
jim Avatar asked Oct 24 '25 00:10

jim


2 Answers

I Suggest you to use LocalStorage , pass in the filter so that it won't be reset. Upon mounting the component , you should always check first if does the localstorage have a value or not.

you can set it via :

localStorage.setItem('variableName', value);

and get it via :

localStorage.getItem('variableName');
like image 191
xSkrappy Avatar answered Oct 25 '25 17:10

xSkrappy


It sounds like A is being created/destroyed every time you switch views, so it loses any state that it was storing.

Move the state up to a parent component of both A and B, and pass it down to A via props. The parent component won't be destroyed, so the state will persist.

Thinking in React may help clarify this.

like image 26
JW. Avatar answered Oct 25 '25 17:10

JW.