Next.js Discord

Discord Forum

useState not working on client-side

Answered
Sloth bear posted this in #help-forum
Open in Discord
Sloth bearOP
Hi, I'm developing an app which has some user validations and stores a JSON Web Token (JWT) as a context in it.

the problem is, when I do useRouter().push($path) in my client-side page, the context data is gone.

for more context on the problem, I'm developing an Wails application with a NextJS front-end and have my next.config.mjs as follow:
/** @type {import('next').NextConfig} */
const nextConfig = {
    output: "export",
    distDir: "dist",
    compress: true,
    async redirects() {
        return [
            {
                source: '/',
                destination: '/login',
                permanent: true,
            },
        ]
    },
};

export default nextConfig;


and here is my context:
import { ReactElement, ReactNode, createContext, useContext, useState, Dispatch } from "react";

type UserContextType = {
    token: string;
    setToken: Dispatch<React.SetStateAction<string>>;
}

const UserContext = createContext<UserContextType | undefined>(undefined);

export function UserContextProvider({children}: { children: ReactNode }): ReactElement<any, any> {
    const [token, setToken] = useState<string>("");
    return (
        <UserContext.Provider value={{token, setToken}}>
            { children }
        </UserContext.Provider>
    )

}

export function useUserContext(): UserContextType {
    const context = useContext(UserContext);
    if (context === undefined) {
        throw new Error('useUserContext must be used within a UserContextProvider');
    }

    return context;
}


when I check the token in another page with useUserContext after the redirect, the content of it is "".
Answered by Sloth bear
ok, I've fixed it, it was the asynchronous behaviour of useState and useContext.
View full answer

3 Replies

Sloth bearOP
ok, turns out that the setToken function is not working.
Sloth bearOP
strange that useState works just fine in any page, but not in my context.
Sloth bearOP
ok, I've fixed it, it was the asynchronous behaviour of useState and useContext.
Answer