Reputation: 195
I have a array in React which is to be shown using useEffect
. That thing got from the previous component to next component. Now, I am using useEffect
to set the array on page load using useState
. But when I refreshes the page, the array gets undefined and the page goes blank. How to get the array again, so that it never throws me error even if I reload the page.
I have used sessionStorage
and localStorage
. But nothing is working out for me.
This is the code I have done so far:
const location = useLocation();
useEffect(() => {
console.log(location.groupsname);
sessionStorage.setItem('groups', JSON.stringify(location.groupsname));
const a = JSON.parse(sessionStorage.getItem('groups'));
console.log(a);
setimportedgroups(a);
}, []);
How should I resolve that?. Thank you.
Upvotes: 1
Views: 1324
Reputation: 203472
You are close. The issue here is that you are wiping out any saved storage value when the component mounts again.
useEffect(() => {
// setting storage is synchronous
sessionStorage.setItem('groups', JSON.stringify(location.groupsname));
// getting the value just set
const a = JSON.parse(sessionStorage.getItem('groups'));
console.log(a);
setimportedgroups(a);
}, []);
If, upon page reload, location.groupsname
is undefined then this is what is stored and loaded back from storage.
You'll want to use a state initializer function and two useEffect
hooks, 1 to persist to storage local state when it updates, and a second to update local state when the location groupsname
updates and has a defined value.
const location = useLocation();
// initialize state from storage on mount
const [importedGroups, setImportedGroups] = useState(() => {
const groups = sessionStorage.getItem('groups');
return JSON.parse(groups) ?? {};
});
// persist importedGroups state to storage
useEffect(() => {
sessionStorage.setItem('groups', JSON.stringify(importedGroups));
}, [importedGroups]);
// update local state when location.groupsname updates
useEffect(() => {
if (location.groupsname) {
setImportedGroups(location.groupsname);
}
}, [location.groupsname]);
Upvotes: 3