Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useState with array giving odd results

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

What I’m missing?

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading