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 tostateOne
- Where it has
name
2
add that object tostateTwo
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)
}
setState functions as an assignment. Like you would normally assign a variable. That means if you want to add something to an array, you need to include that array in the assignment.
Something like this:
I’d prefer sending
data
as a prop to that componentYou can achieve what you need by
If you don’t want to use filter twice for whatever reason, You can create temporary array for each one and manipulate them then update each state respectively like so:
The problem with what you’re doing is you’re updating the state each time you find a match which will cause a lot of unnecessary re-renders.
You’ve said that
data
comes from some API you’re querying. If so, filter the data once you get it. You can do that in a couple of ways.With two calls to
filter
:Or if you don’t want to make two passes through the data, a single loop: