Home > Back-end >  Conditionally updating state with prevState not working
Conditionally updating state with prevState not working

Time:07-10

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

What am I doing wrong?

CodePudding user response:

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))
  • Related