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
name1add that object tostateOne - Where it has
name2add that object tostateTwo
End goal both states needs to have Array of Objects inside:
stateOneneeds to look like
[
{ id: '1', name: '1' },
{ id: '2', name: '1' }
]
stateTwoneeds 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)
}
datareally static and defined outside theTestingcomponent like that? If so, why theuseEffect?filteris to create and return a new array, which it does by creating a new array and either adding entries to it (if your callback returns truthy value) or not. If you don't use the arrayfilterreturns, don't usefilter. Just loop through the array with a simple loop, orforEach.filtertwice which is working. So i know i'm doing something wrong in setState