0

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?

2
  • 1
    Try setResponses([...responses, ...tempResults]) Commented Mar 6, 2020 at 9:39
  • Yes it worked out. I just have to figure out how to handle an array within an array, but that is a different question. Commented Mar 6, 2020 at 9:56

1 Answer 1

1

if res.data.data is an array

then set to setResponses like this

setResponses(res.data.data)

or

setResponses([...responses, ...res.data.data])
Sign up to request clarification or add additional context in comments.

1 Comment

Ok. Now i get the array of objects in the 'responses' state. However, when i access props.responses.map(item.mape), i get an array. So it seems to be a nested array.

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.