Reactjs: TypeError: Cannot read property 'results' of undefined
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
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.
javascript reactjs
add a comment |
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.
javascript reactjs
because you use the varaible before it is set....
– epascarello
Nov 16 '18 at 15:43
@epascarello how so? Do I need to wait for it to be assigned an then make a callback?
– Guilherme P.
Nov 16 '18 at 15:44
Because the fetch call is asynchronous so that code fires AFTER you run the map line. That is why fetch has promises. The code would have to run in the then, but you would not be able to return it. stackoverflow.com/questions/23667086/…
– epascarello
Nov 16 '18 at 15:45
1
Possible duplicate of How do I return the response from an asynchronous call?
– ponury-kostek
Nov 16 '18 at 15:45
add a comment |
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.
javascript reactjs
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.
javascript reactjs
javascript reactjs
asked Nov 16 '18 at 15:41
Guilherme P.Guilherme P.
588
588
because you use the varaible before it is set....
– epascarello
Nov 16 '18 at 15:43
@epascarello how so? Do I need to wait for it to be assigned an then make a callback?
– Guilherme P.
Nov 16 '18 at 15:44
Because the fetch call is asynchronous so that code fires AFTER you run the map line. That is why fetch has promises. The code would have to run in the then, but you would not be able to return it. stackoverflow.com/questions/23667086/…
– epascarello
Nov 16 '18 at 15:45
1
Possible duplicate of How do I return the response from an asynchronous call?
– ponury-kostek
Nov 16 '18 at 15:45
add a comment |
because you use the varaible before it is set....
– epascarello
Nov 16 '18 at 15:43
@epascarello how so? Do I need to wait for it to be assigned an then make a callback?
– Guilherme P.
Nov 16 '18 at 15:44
Because the fetch call is asynchronous so that code fires AFTER you run the map line. That is why fetch has promises. The code would have to run in the then, but you would not be able to return it. stackoverflow.com/questions/23667086/…
– epascarello
Nov 16 '18 at 15:45
1
Possible duplicate of How do I return the response from an asynchronous call?
– ponury-kostek
Nov 16 '18 at 15:45
because you use the varaible before it is set....
– epascarello
Nov 16 '18 at 15:43
because you use the varaible before it is set....
– epascarello
Nov 16 '18 at 15:43
@epascarello how so? Do I need to wait for it to be assigned an then make a callback?
– Guilherme P.
Nov 16 '18 at 15:44
@epascarello how so? Do I need to wait for it to be assigned an then make a callback?
– Guilherme P.
Nov 16 '18 at 15:44
Because the fetch call is asynchronous so that code fires AFTER you run the map line. That is why fetch has promises. The code would have to run in the then, but you would not be able to return it. stackoverflow.com/questions/23667086/…
– epascarello
Nov 16 '18 at 15:45
Because the fetch call is asynchronous so that code fires AFTER you run the map line. That is why fetch has promises. The code would have to run in the then, but you would not be able to return it. stackoverflow.com/questions/23667086/…
– epascarello
Nov 16 '18 at 15:45
1
1
Possible duplicate of How do I return the response from an asynchronous call?
– ponury-kostek
Nov 16 '18 at 15:45
Possible duplicate of How do I return the response from an asynchronous call?
– ponury-kostek
Nov 16 '18 at 15:45
add a comment |
1 Answer
1
active
oldest
votes
To do this correctly you should call setState()
in the promise chain.
.then(data => {
results = data;
this.setState({results});
console.log(results);
}
Then you can create the <li>
elements in render()
:
render() {
const mapCats = Object.keys(this.state.results.results).map(key =>
<li key={key}>{this.state.results.results[key].name}</li>
);
// ...
}
Note that I am assuming the function that calls fetch()
is inside your class. You can do what you want with a global function, but it is a little more complex. The basic idea is the same, though.
That worked. I changed my function to a class, added an empty Array do my state and passed my results to it. Thanks. I'm just waiting until I can mark your answer as the correct one.
– Guilherme P.
Nov 16 '18 at 15:55
@GuilhermeP. Glad to hear that you filled in the details missing from my answer.
– Code-Apprentice
Nov 16 '18 at 17:30
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53341080%2freactjs-typeerror-cannot-read-property-results-of-undefined%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
To do this correctly you should call setState()
in the promise chain.
.then(data => {
results = data;
this.setState({results});
console.log(results);
}
Then you can create the <li>
elements in render()
:
render() {
const mapCats = Object.keys(this.state.results.results).map(key =>
<li key={key}>{this.state.results.results[key].name}</li>
);
// ...
}
Note that I am assuming the function that calls fetch()
is inside your class. You can do what you want with a global function, but it is a little more complex. The basic idea is the same, though.
That worked. I changed my function to a class, added an empty Array do my state and passed my results to it. Thanks. I'm just waiting until I can mark your answer as the correct one.
– Guilherme P.
Nov 16 '18 at 15:55
@GuilhermeP. Glad to hear that you filled in the details missing from my answer.
– Code-Apprentice
Nov 16 '18 at 17:30
add a comment |
To do this correctly you should call setState()
in the promise chain.
.then(data => {
results = data;
this.setState({results});
console.log(results);
}
Then you can create the <li>
elements in render()
:
render() {
const mapCats = Object.keys(this.state.results.results).map(key =>
<li key={key}>{this.state.results.results[key].name}</li>
);
// ...
}
Note that I am assuming the function that calls fetch()
is inside your class. You can do what you want with a global function, but it is a little more complex. The basic idea is the same, though.
That worked. I changed my function to a class, added an empty Array do my state and passed my results to it. Thanks. I'm just waiting until I can mark your answer as the correct one.
– Guilherme P.
Nov 16 '18 at 15:55
@GuilhermeP. Glad to hear that you filled in the details missing from my answer.
– Code-Apprentice
Nov 16 '18 at 17:30
add a comment |
To do this correctly you should call setState()
in the promise chain.
.then(data => {
results = data;
this.setState({results});
console.log(results);
}
Then you can create the <li>
elements in render()
:
render() {
const mapCats = Object.keys(this.state.results.results).map(key =>
<li key={key}>{this.state.results.results[key].name}</li>
);
// ...
}
Note that I am assuming the function that calls fetch()
is inside your class. You can do what you want with a global function, but it is a little more complex. The basic idea is the same, though.
To do this correctly you should call setState()
in the promise chain.
.then(data => {
results = data;
this.setState({results});
console.log(results);
}
Then you can create the <li>
elements in render()
:
render() {
const mapCats = Object.keys(this.state.results.results).map(key =>
<li key={key}>{this.state.results.results[key].name}</li>
);
// ...
}
Note that I am assuming the function that calls fetch()
is inside your class. You can do what you want with a global function, but it is a little more complex. The basic idea is the same, though.
answered Nov 16 '18 at 15:46
Code-ApprenticeCode-Apprentice
49k1492180
49k1492180
That worked. I changed my function to a class, added an empty Array do my state and passed my results to it. Thanks. I'm just waiting until I can mark your answer as the correct one.
– Guilherme P.
Nov 16 '18 at 15:55
@GuilhermeP. Glad to hear that you filled in the details missing from my answer.
– Code-Apprentice
Nov 16 '18 at 17:30
add a comment |
That worked. I changed my function to a class, added an empty Array do my state and passed my results to it. Thanks. I'm just waiting until I can mark your answer as the correct one.
– Guilherme P.
Nov 16 '18 at 15:55
@GuilhermeP. Glad to hear that you filled in the details missing from my answer.
– Code-Apprentice
Nov 16 '18 at 17:30
That worked. I changed my function to a class, added an empty Array do my state and passed my results to it. Thanks. I'm just waiting until I can mark your answer as the correct one.
– Guilherme P.
Nov 16 '18 at 15:55
That worked. I changed my function to a class, added an empty Array do my state and passed my results to it. Thanks. I'm just waiting until I can mark your answer as the correct one.
– Guilherme P.
Nov 16 '18 at 15:55
@GuilhermeP. Glad to hear that you filled in the details missing from my answer.
– Code-Apprentice
Nov 16 '18 at 17:30
@GuilhermeP. Glad to hear that you filled in the details missing from my answer.
– Code-Apprentice
Nov 16 '18 at 17:30
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53341080%2freactjs-typeerror-cannot-read-property-results-of-undefined%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
because you use the varaible before it is set....
– epascarello
Nov 16 '18 at 15:43
@epascarello how so? Do I need to wait for it to be assigned an then make a callback?
– Guilherme P.
Nov 16 '18 at 15:44
Because the fetch call is asynchronous so that code fires AFTER you run the map line. That is why fetch has promises. The code would have to run in the then, but you would not be able to return it. stackoverflow.com/questions/23667086/…
– epascarello
Nov 16 '18 at 15:45
1
Possible duplicate of How do I return the response from an asynchronous call?
– ponury-kostek
Nov 16 '18 at 15:45