I have tried several other options on how to do this, such as
How to read a nested JSON in React?
Can't access nested JSON Objects in React
I am trying to query the API when I click "Search". Currently, when I click "Search", the API queries the correct URL, but I am having trouble accessing the returned data. The data that is sent back looks like this:
{
"option_activity": [
{
"id": "5f033b253c8cf100018a312f",
"bid": "0.6",
"ask": "1.0",
"midpoint": "0.8",
"updated": 1594047269
},
{
"id": "5f033b253c8cf100018a312f",
"bid": "0.6",
"ask": "1.0",
"midpoint": "0.8",
"updated": 1594047269
},
With hundreds of these items. What it looks like in the console:
What I am doing to query the api:
fetchData() {
var val = this.state.searchedValue;
var url = "URL/TO/API"
fetch(url)
.then(res => res.json())
.then((res) => {
const itemsList = res.option_activity;
this.setState({
items: itemsList
},
function () {
console.log(itemsList);
}
);
// console.log(this.state.items)
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
console.log(error);
},
// console.log(this.state.items)
)
}
While the network logs the response from the API, the console log just logs an empty array "[]" for this.state.items, which is initialized to an empty array. How can I save the contents of "option_activity" into an array "items", where I can access the id, bid, ask, midpoint etc through this array of items?
So, items[0] would have items[0].id, items[0].midpoint, etc accessible.
Thanks in advance
Solution is in the comments of the correctly marked answer

idfor each element, so it seems like it's not enough code to reproduce the problem. If you want the full structure, remove themapcall. Are you getting any errors? The onlyconsole.logis in the error handler so it'd make sense that that would be empty if it does fire.console.logis happening in the error function, are you sure there isn't an error occuring before setting those items to the state?