I have a NextJS project in which I have this code
const getStoragePlayers = () => {
return LocalStorageUtility.read(LocalStorageUtility.playersKey) as PlayerInterface[]
}
const TakeAShare: NextPage = () => {
const [players, setPlayers] = useState<PlayerInterface[]>(getStoragePlayers())
}
But when I render I get the "ReferenceError: localStorage is not defined" error.
Browsing a little I've found a solution, look if localStorage is defined:
const getStoragePlayers = () => {
return typeof localStorage !== 'undefined'
? LocalStorageUtility.read(LocalStorageUtility.playersKey) as PlayerInterface[]
: []
}
But then I get "Error: Hydration failed because the initial UI does not match what was rendered on the server."
How can I solve it?
p.s. I can't use the useEffect(() => {[...]}, []) because it affects badly on other components.
p.p.s LocalStorageUtility is a utility I have created to manage more easily the localStorage
EDIT: I have solved removing localStorage and using Zustand