How to add more objects to Array Object state using setState?

This is my initial data

const data = [
  { id: '1', name: '1' },
  { id: '2', name: '1' },
  { id: '3', name: '2' },
]

I want to loop over and:

  • Where it has name 1 add that object to stateOne
  • Where it has name 2 add that object to stateTwo

End goal both states needs to have Array of Objects inside:

  • stateOne needs to look like
[
  { id: '1', name: '1' },
  { id: '2', name: '1' }
]
  • stateTwo needs to look like
[
  { id: '3', name: '2' },
]

This is what i’ve tried:

const data = [
  { id: '1', name: '1' },
  { id: '2', name: '1' },
  { id: '3', name: '2' },
]

const Testing = () => {
  const [stateOne, setStateOne] = useState([])
  const [stateTwo, setStateTwo] = useState([])

  useEffect(() => {
    data.forEach((e) => {
      if (e.name === '1') {
        console.log('e', e)
        setStateOne((prevSate) => ({ ...prevSate, e }))
      }
      // if (e.name === '2') {
      //   setStateTwo(e)
      // }
    })
  }, [])

  console.log('stateOne', stateOne)
}

155 thoughts on “How to add more objects to Array Object state using setState?”