2

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])

3 Answers 3

4

Spread the newData so you get a single flat array in the new state.

setState([...state, ...newData]);

Or

setState(state.concat(newData));
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.