I have an array of participant components that i construct from participants list like this:
function parent({addr}){
const [winner, setWinner] = useState(null);
const [participants,setParticipants] = useState([{id:0,name:"user0"}]);
useEffect(()=>
{
participants.map((elem,index)=> <Participant key={index} participant={elem} winner={winner}/>);
countWinner();
},[addr])
function countwinner()
{
setWinner(prev => {return {id:0,count:5}})
}
}
inside the child component; i monitor the change of winner by using useEffect():
function Participant({winner})
{
useEffect(()=>
{
console.log("winner variable changed",winner)
},[winner]);
}
the output of logging winner is always null
.
PS: I added useEffect inside parent and it is updating correctly, it just does not update in the child list.
CodePudding user response:
what you done wrong is:
- just change this line
setWinner(prev => {return {id:0,count:5}}) to
setWinner(prev => ({id:0,count:5}))`. - what the hell you are using map in
useEffect
.
take a look to this snippet of parent.
import React, { useState, useEffect } from 'react';
import Participant from './Participant';
function Parent({ addr }) {
const [winner, setWinner] = useState(null);
const [participants, setParticipants] = useState([{ id: 0, name: 'user0' }]);
useEffect(() => {
countWinner();
}, [addr]);
function countWinner() {
setWinner((prev) => ({ id: 0, count: 5 }));
}
return participants.map((elem, index) => (
<Participant key={index} participant={elem} winner {...winner} />
));
}
export default Parent;