I am having a small problem with my code.
So, this is the first time I am trying to implement context on a project but I am getting an error:
Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))
I guess is because the object is not being accessed by the child component.
Here is the parent component (My Routes)
import {UserContext} from "../Context/UserContext"
function WebRoutes() {
const [user,setUser]=useState(null);
return (
<UserContext.Provider value={(user,setUser)}>
<Router>
<Routes>
<Route path="/" element={<Login/>}/>
<Route path="/home" element={<Home/>}/>
<Route path="/departaments" element={<Departaments/>}/>
<Route path="/product/:id" element={<Product/>}/>
<Route path="*" element={<NotFound/>}/>
</Routes>
</Router>
</UserContext.Provider>
)
}
This one will be the child component:
import React, {useState, useContext} from 'react'
import {UserContext} from '../../Context/UserContext';
const [user,setUser]=useContext(UserContext)
That's the way I am trying to get the context.
I am not sure where I am wrong.
This is the UserContext file:
import {createContext} from "react"
export const UserContext = createContext(null);
I would appreciate any kind of help. I am trying to achieve this by using a course.
Thanks a lot in advance.
CodePudding user response:
Issue
value={(user, setUser)}
You are providing the context value incorrectly as a comma operator result.
The comma operator (
,
) evaluates each of its operands (from left to right) and returns the value of the last operand.
This means you are providing only the setUser
function as the context value.
Solution
If you are expecting the UserContext
to return an array:
const [user, setUser] = useContext(UserContext);
Then you should provide an array value:
function WebRoutes() {
const [user, setUser] = useState(null);
return (
<UserContext.Provider value={[user, setUser]}> // <-- array
<Router>
<Routes>
<Route path="/" element={<Login />} />
<Route path="/home" element={<Home />} />
<Route path="/departaments" element={<Departaments />} />
<Route path="/product/:id" element={<Product />} />
<Route path="*" element={<NotFound />} />
</Routes>
</Router>
</UserContext.Provider>
);
}