Next.js Discord

Discord Forum

Access either localstorage or cookies in a contextProvider

Answered
Pavement ant posted this in #help-forum
Open in Discord
Avatar
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:
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.
View full answer

3 Replies

Avatar
Initialize the useStates as empty and just wrap the localStorage code inside useEffect with empty dependency.
Answer
Avatar
Wait why do you need async for cookies?
Avatar
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');