I'm fetching data from a Rest API, which returns me an Object with an Array of results. When I try mapping through it, it gives me the following error:
TypeError: Cannot read property 'results' of undefined
function Teste() {
let results;
fetch('https://parseapi.back4app.com/classes/MyClass', {
method: 'GET',
headers: {
'X-Parse-Application-Id': 'MyKey',
'X-Parse-REST-API-Key': 'MyKey',
'X-Parse-Master-Key': 'MeyKey'
}
}).then(response => {
return response.json();
}).then(data => {
results = data;
console.log(results);
}).catch(error => {
console.log(error);
});
const mapCats = Object.keys(results.results).map(key =>
<li key={key}>{results.results[key].name}</li>
);
return (
mapCats
);
}
The output of the results is this:
{
"results": [
{
"objectId": "JoT2miD1vo",
"name": "Mercado",
"createdAt": "2018-11-08T13:49:25.600Z",
"updatedAt": "2018-11-08T13:50:08.721Z"
},
{
"objectId": "DEuZHY7BwY",
"name": "Panificadora",
"createdAt": "2018-11-08T13:49:40.385Z",
"updatedAt": "2018-11-08T17:06:09.129Z"
},
{
"objectId": "V3g1FXNtLK",
"name": "Farmácia",
"createdAt": "2018-11-08T13:50:02.293Z",
"updatedAt": "2018-11-08T13:50:02.293Z"
},
{
"objectId": "Psl9GWqB4F",
"name": "Loja",
"createdAt": "2018-11-08T13:50:34.696Z",
"updatedAt": "2018-11-08T13:50:34.696Z"
},
{
"objectId": "ezlncu6cd1",
"name": "Lanchonete",
"createdAt": "2018-11-08T13:50:41.649Z",
"updatedAt": "2018-11-08T13:50:41.649Z"
},
{
"objectId": "vDgxIW69rr",
"name": "Sorveteria",
"createdAt": "2018-11-08T13:50:54.824Z",
"updatedAt": "2018-11-08T13:50:54.824Z"
},
{
"objectId": "VdxckEDG7q",
"name": "Food Truck",
"createdAt": "2018-11-08T13:51:14.096Z",
"updatedAt": "2018-11-08T13:51:14.096Z"
},
{
"objectId": "LHrGCT9SCs",
"name": "Pizzaria",
"createdAt": "2018-11-08T16:12:48.317Z",
"updatedAt": "2018-11-08T16:12:48.317Z"
}
]
}
When I declare this object as a constant in my code, it returns me no errors and the mapping works. But when I try assigning the results
of data
it won't work.