'I am having issues with the object data gotten from my localstorage in my nextjs project

I get an object from my local storage and store it in a constant obj2. The object data gotten from my local storage is the same as the obj1 constant.

 const obj1 = 
    {
      "items":[{"id":"61f92717428e9e5b47de4445","name":"Yoghurt"}],
      "total":400,
      "isEmpty": false
    };

 const obj2 = JSON.parse(localStorage.getItem('item')!); 

The console.log of obj1 and obj1.total outputs successfully. The obj2 output as well, but obj2.total shows undefined. And it's the same object stored in obj1 that is in obj2 local storage.

function MapObj() {

    const obj1 = 
    {
      "items":[{"id":"61f92717428e9e5b47de4445","name":"Yoghurt"}],
      "total":400,
      "isEmpty": false
    };
    console.log(obj1);
    console.log(obj1.total); 

    const obj2 = JSON.parse(localStorage.getItem('item')!); 
    console.log(obj2); 
    console.log(obj2.total); 


return (
    <div>
      <h1>God's Plan</h1>
    </div>
  )


    }
export default MapObj

I have spent lots of time trying to figure out what the issue is, but no outcome yet! What might be the issue?.



Solution 1:[1]

when using localStorage, after you call setitem, you need will need to refresh the page. Nextjs or React is single page application, so you dont want to refresh your app!

Here is a packge you can use to interact with localStorage. Here is a link to try it out this link, I am using it in combination with useContext.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shaynel