skip to Main Content

TL;DR I’ve got a context which seems fine (to my untrained eye) but its values when I go useContext are undefined.

export const AuthProvider = ({children}) => {
    const [isLoading, setIsLoading] = useState(false);
    const [userToken, setUserToken] = useState(null);

    return (
        <AuthContext.Provider value="{{ isLoading, userToken }}"> 
            {children}
        </AuthContext.Provider>
    );
}

I’m using the provider to wrap:

<AuthProvider>
   <AppNav></AppNav>
</AuthProvider>

And then trying to use the values from the context:

const AppNav = () => {
    //console.log("useContext(context): ", useContext(AuthContext));
    const {isLoading, userToken} = useContext(AuthContext)
    
    console.log(`in AppNav userToken is: ${userToken}`);
    console.log(isLoading);
    ...

My commented out console.log showed me that the context is {{ isLoading, userToken }}, so that seems… fine?

But then my other console.log shows me that all the values are undefined.

You’re my last hope, stack overflow – I’ve been trying to figure this out for hours.

2

Answers


  1. I can see that you are making a syntax error, it should be

    value={{ isLoading, userToken }}
    

    So your code should be:

    export const AuthProvider = ({children}) => {
        const [isLoading, setIsLoading] = useState(false);
        const [userToken, setUserToken] = useState(null);
    
        return (
            <AuthContext.Provider value={{ isLoading, userToken }}>
                {children}
            </AuthContext.Provider>
        );
    }
    
    Login or Signup to reply.
  2. Should be <AuthContext.Provider value={{ isLoading, userToken }}>

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search