Reputation: 35
I'm trying to add each element of an array I pull from an API into an existing state in react. How would I be able to pull out each element and add it to state?
Here is what I know how to do. It doesn't work in this situation because the new data is an array.
state= [{}, {}, {}]
newData= [{}, {}, {}]
setState([...state, newData])
Upvotes: 2
Views: 1038
Reputation: 116
In react, Array.map is used to run through an array and get each element.
If the API call is through user input, you can change the state as-
this.setState={i: this.state.i + 1}
Assuming your items have properties-name, location, age etc.. example:
{array.map((item,index)=>{
return (
<div key={index} >
{index === i && (
<Component
name={item.name}
location={item.location}
age={item.age}
/>
)}
</div>
)
})}
If i changes on user input, each object's index in the array will match 'i' and UI will change. The items in each object will be added to the component as a prop.
Upvotes: 1
Reputation: 1088
You should use a spread operator for every array item. And set state only when the newData has an array value.
if ( Array.isArray(newData) ) {
setState([...state, ...newData]);
}
Please let me know if it works or not.
Upvotes: 1
Reputation: 370759
Spread the newData
so you get a single flat array in the new state.
setState([...state, ...newData]);
Or
setState(state.concat(newData));
Upvotes: 4