Chakra
Chakra

Reputation: 2557

How to push array of objects into state using hooks

I have a useState as const [responses, setResponses] = useState([]);

I get the response and log it as follows :

const tempResults = res.data.data;
console.log(tempResults.length);
console.log(tempResults);

The log shows as:

enter image description here

When I click to open the Array of 6 items, results are enter image description here. So it is an array of objects. I tried to set the initial value of the state as per the object

{
  "index": 0,
  "ds": "2020-03-06",
  "yhat_lower": -10712.5597359237,
  "yhat_upper": 25376.4649581317,
  "yhat": 6955.3671910982,
  "mape": 21.4472070205,
  "rmse": 667.0969808414,
  "mae": 475.3343871057,
  "smape": 5.143548286
}

But when I logged, the state only had the initial value and had not appended the response array.

I am setting state as :

setResponses(...responses, tempResults);
const x = typeof responses;
console.log("TypeOfResponse", x);
console.log("RESPONSES ", responses);

However, the state of the 'responses' object as per console is this:

enter image description here

So it is not able to save the Array object into state. What could be wrong? Any suggestions, please?

Upvotes: 0

Views: 109

Answers (1)

akhtarvahid
akhtarvahid

Reputation: 9769

if res.data.data is an array

then set to setResponses like this

setResponses(res.data.data)

or

setResponses([...responses, ...res.data.data])

Upvotes: 1

Related Questions