'React dobble update so my useContext = undefined
Hi i have a problem with my react app, I'm using useContext to parse my user to a voting site, but I have a small problem, my app is dobble loading, then my context turns to undefined, i can see the user at the first console.log but i cannot access it.
const { user, setUser } = useContext(UserContext)
const [medarbejdere, setMedarbejdere] = useState({})
const userLogIn = document.getElementById('id').value;
const user = medarbejdere?.filter(userid => userid.id === parseInt(userLogIn)).map(currentUser => console.log(currentUser))
setUser(user);
navigate("/votingsite")```
Solution 1:[1]
console.log is a void return, you are mapping a currentUser value to undefined and then updating likely the user state to an array of undefined values. Don't use Array.prototype.map for side-effects like console logging a value.
const { user, setUser } = useContext(UserContext);
const [medarbejdere, setMedarbejdere] = useState({});
const userLogIn = document.getElementById('id').value;
const user = medarbejdere?.filter(userid => userid.id === parseInt(userLogIn));
// console log the entire `user` array
console.log(user);
// or use `Array.protype.forEach` to issue side-effect on each element
user.forEach(currentUser => console.log(currentUser));
You also may be seeing the setUser and navigate calls as unintentional side-effects because they are in the component body. These should be in a callback or useEffect hook.
useEffect(() => {
setUser(user);
navigate("/votingsite");
}, []);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Drew Reese |
