Home > database >  useState with array giving odd results
useState with array giving odd results

Time:11-20

I'm facing an issue with the react useState with arrays, this is my teamMembers state declaration:

const [teamMembers, setTeam] = useState();

...and I'm filling a form and, on click of a button, updating the teamMembers state. the below code is inside a handler:

let newTeam = teamMembers || ['Tony Stark'];

console.log(newTeam);    // here it is giving me Tony Stark
setTeam(newTeam);

I have used useEffect to see the update:

useEffect(() => {
    console.log(teamMembers);     // here it is giving me empty array([])
})

What I'm missing?

CodePudding user response:

Should set to an empty array first:

const [teamMembers, setTeam] = useState([])

Then:

useEffect(() => {
   console.log(teamMembers)
}, [teamMembers])

If array ever changes useEffect will log an empty array.

Think you're trying to do:

const [teamMembers, setTeam] = useState([])

setTeam([...teamMembers, 'Tony stark'])

useEffect(() => {
   console.log(teamMembers)
}, [teamMembers])

CodePudding user response:

correction in third block might work:

useEffect(() => {
   console.log(teamMembers);     // here it is giving me empty array([])
},[teamMembers]);
  • Related