Access either localstorage or cookies in a contextProvider
Answered
Pavement ant posted this in #help-forum
Pavement antOP
Hi, I'm trying to setup state management on the application to track the logged in user. I've used the same type of context on normal React but I'm having a few issues with nextjs/SSR.
Here is the code:
Basically I need to store / get the user from either cookies or localstorage, but localstorage is not available, and cookies won't work in a sync function (and I cannot set it as async, since it wouldn't allow me to use it as a dom element).
Is there a workaround to make the above code work?
Here is the code:
import { createContext, useState } from "react"
import { cookies } from 'next/headers'
export const UserDataContext = createContext()
export default function UserDataContextManager(props) {
const cookieStore = cookies()
const [user, setUser] = useState({
user: JSON.parse(cookieStore.get('user') || '{}'),
setUserData: (user) => {
setUser((current) => ({ ...current, user: user }))
cookieStore.set('user', JSON.stringify(user || {}))
}
})
return (
<UserDataContext.Provider value={user}>
{props.children}
</UserDataContext.Provider>
)
}
Basically I need to store / get the user from either cookies or localstorage, but localstorage is not available, and cookies won't work in a sync function (and I cannot set it as async, since it wouldn't allow me to use it as a dom element).
Is there a workaround to make the above code work?
Answered by Sohel Shekh
Initialize the useStates as empty and just wrap the localStorage code inside useEffect with empty dependency.
3 Replies
Initialize the useStates as empty and just wrap the localStorage code inside useEffect with empty dependency.
Answer
Wait why do you need async for cookies?
Pavement antOP
@DirtyCajunRice | AppDir Method expects to have requestAsyncStorage, none available
For some reasons, the package cookie-next works for the above, using getCookie('user');
For some reasons, the package cookie-next works for the above, using getCookie('user');