Skip to content
Advertisement

Updating the localStorage is not in sync

When I toggle darkmode it doesn’t update in _app unless I have 2 tabs opened and trigger it in one tab, then the other tab gets updated and darkmode is toggled, but not the tab I pressed the toggle. I use useSettings in both index and _app. I recorded a video so it’s easier to see what’s going on: https://youtu.be/W5du7Y-457Y.

JavaScript

Index

JavaScript

_app

JavaScript

Advertisement

Answer

When you update the localStorage, the document that’s updating does not get noticed with its event listener. Here is a quote from mdn:

This won’t work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can’t access the same storage objects.

The solution is to add the below line after each localStorage.setItem(...):

JavaScript

To adapt to your use case, create a function called for example updateTheme inside useLocalStorage:

JavaScript

And you return the above function instead of setValue, like so:

JavaScript

And remove that useEffect you have:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement