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

Conditionally updating state with prevState not working

I’m trying to update state, which is an array of objects, only if the object I’m trying to add isn’t already present in the state.

setTogglerStateArray((prevState) => {
    console.log('data:')
    console.log(data)
    console.log('prevState:')
    console.log(prevState)

    if (prevState.includes(data)) {
        return prevState
    } else {
        return [...prevState, data]
    }

})

And what comes out in console:

enter image description here

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

What am I doing wrong?

>Solution :

You can not use includes to check if a whole object is in an array. you could use .find or Array.some

if (prevState.some(({ user_id, convo_id, revealed})=> user_id === data.user_id && convo_id === data.convo_id &&  revealed === data.revealed))
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