#How can I get value stored in session storage in next.js?

4 messages · Page 1 of 1 (latest)

viral moth
#

Hello everyone. I am new to Next.js and I need someone's help. I have a slider component where users can set number of columns in my ImageGallery component. I am trying to store the value from slider in session storage so I can save user preference, and display preferred number of columns. Then in my home page (static page) i render ImageGallery Component.

Storing data works as intended. The problem I face is that whenever I go back to homepage it sets the value as null regardless of what was stored in session storage (it overrides session storage). Can someone help me to solve this problem?

Here is the link to my stackoverflow question with the code:
https://stackoverflow.com/questions/75363316/how-can-i-get-value-stored-in-session-storage-next-js

Many thanks in advance, and I hope my problem is clear.

old quail
#

Remove the first useEffect and change the callback like this:

const handleChange = (event: any) => {
  window.sessionStorage.setItem("value", JSON.stringify(event.target.value));
  setValue(event.target.value);
};
viral moth
#

Dear Somebody,

I have no words to say how grateful I am :D. I really have spent some time trying to figure it out. I changed in the useState(null) instead of null I initiate it with 1 and it works as intended.

Perhaps you could explain to me why my solution was not working as it seems to me that useEffect supposed to set new value to session storage every time the new value is set?

Anyway huge thanks!

old quail
#

useEffect gets triggered on the first render, so when the default value was set, this would be called:

useEffect(() => {
  if (typeof window !== "undefined") {
    // Always sets the localStorage item to null when the Component is mounted
    window.sessionStorage.setItem("value", JSON.stringify(value));
  }
}, [value]);

As a general rule of thumb: If your useEffect depends on a state, there might be something wrong with the logic. As states can only be changed via set-callback, you can always put your logic where you also set the state, instead of putting it into a useEffect that reacts to changes of that state. This might also help you to avoid unnecessary re-renders.