Problem with the context api

I am trying to authenticate a login form.After using context api it showed the error.



Please help me.I got stuck.

Can you post the code of your context provider? I think the value has to be an object, but you’re trying Array destructuring here:

const [loggedInUser, setLoggedInUser] = useContext(UserContext)

export const UserContext = createContext();

function App() {

const [loggedInUser,setLoggedInUser] = useState({});

return (

<UserContext.Provider value={[loggedInUser,setLoggedInUser]}>

   <Router>

  <Header></Header>

    <Switch>

        <Route exact path="/">

          <Home/>

         </Route>

        <Route path="/home">

          <Home/>

         </Route>

        <Route path="/blog">

          <Blog/>

         </Route>

        <Route path="/contact">

          <Contact/>

         </Route>

        

        <PrivateRoute path="/destination/:id">

          <Destination></Destination>

        

        </PrivateRoute> 

        

        <PrivateRoute path="/finalDestination/:id">

         <FinalDestination />

        

        </PrivateRoute> 

        <Route path="/login">

          <LogIn></LogIn>

      

        </Route> 

        <Route path="*">

          <NotFound />

        </Route>

       

    </Switch>

  </Router>

</UserContext.Provider>

);

}

export default App;

Your state is an empty object:

function App() {

  const [loggedInUser,setLoggedInUser] = useState({});

  return (

    <UserContext.Provider value={[loggedInUser,setLoggedInUser]}>
...

Then you try to destructure that empty object, which cannot work:

const [loggedInUser, setLoggedInUser] = useContext(UserContext)

Just to expand on that: value has to be an object. But what you’ve done is just chucked that destructured array straight in there, it’s not really a React error, it’s a JS syntax error. This will work:

value={{ loggedInUser, setLoggedInUser }};

So, if I write that out longhand, what above is is:

const myContextProperties = {
  loggedInUser: loggedInUser,
  setLoggedInUser: setLoggedInUser,
};

// Then
<UserContext.Provider value={myContextProperties}>

Atm it’s kinda trying to parse something like

const myContextProperties = {
  [loggedInUser, setLoggedInUser]
}

Which isn’t at all the correct syntax for an object, it just blows up

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.