Can't access Javascript object within React Component
So, I'm getting stuck into React and it's already making me scratch my head..
I am grabbing some API data like and trying to access any particular index or loop through - whatever I do, it does not seem to work!
Here is the main component:
class App extends React.Component {
const CityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff'];
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items:
};
}
// Fire our function below on app load
componentDidMount() {
this.getWeather();
}
// getWeather - make api call
getWeather = () => {
let results = ;
// Loop through our cities list here to gather data
// We will then push this into this.state.results
CityListNames.forEach(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
// get api data
fetch(api_url)
.then(res => res.json())
.then(
(result) => {
results.push(result);
console.log(result[0]);
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
});
this.setState({
isLoaded: true,
items: results
});
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
When I use console.log(result[0]);
it simply outputs as "undefined" in the console.
I am trying to assign all values to the results variable and then push it to the state.
When I do console.log(items) it shows all items as well which is very odd.
API data
Any help would be deeply appreciated!
Thanks
javascript arrays json reactjs
add a comment |
So, I'm getting stuck into React and it's already making me scratch my head..
I am grabbing some API data like and trying to access any particular index or loop through - whatever I do, it does not seem to work!
Here is the main component:
class App extends React.Component {
const CityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff'];
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items:
};
}
// Fire our function below on app load
componentDidMount() {
this.getWeather();
}
// getWeather - make api call
getWeather = () => {
let results = ;
// Loop through our cities list here to gather data
// We will then push this into this.state.results
CityListNames.forEach(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
// get api data
fetch(api_url)
.then(res => res.json())
.then(
(result) => {
results.push(result);
console.log(result[0]);
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
});
this.setState({
isLoaded: true,
items: results
});
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
When I use console.log(result[0]);
it simply outputs as "undefined" in the console.
I am trying to assign all values to the results variable and then push it to the state.
When I do console.log(items) it shows all items as well which is very odd.
API data
Any help would be deeply appreciated!
Thanks
javascript arrays json reactjs
2
fetch()
is asynchronous. What you see in console is not a snapshot. It will represent updates even after it is logged
– charlietfl
Nov 19 '18 at 21:04
2
Possible duplicate of How do I return the response from an asynchronous call?
– hindmost
Nov 19 '18 at 21:06
Do not post images of code or errors! Images and screenshots can be a nice addition to a post, but please make sure the post is still cle ar and useful without them. If you post images of code or error messages make sure you also copy and paste or type the actual code/message into the post directly.
– Rob
Nov 20 '18 at 2:09
add a comment |
So, I'm getting stuck into React and it's already making me scratch my head..
I am grabbing some API data like and trying to access any particular index or loop through - whatever I do, it does not seem to work!
Here is the main component:
class App extends React.Component {
const CityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff'];
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items:
};
}
// Fire our function below on app load
componentDidMount() {
this.getWeather();
}
// getWeather - make api call
getWeather = () => {
let results = ;
// Loop through our cities list here to gather data
// We will then push this into this.state.results
CityListNames.forEach(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
// get api data
fetch(api_url)
.then(res => res.json())
.then(
(result) => {
results.push(result);
console.log(result[0]);
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
});
this.setState({
isLoaded: true,
items: results
});
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
When I use console.log(result[0]);
it simply outputs as "undefined" in the console.
I am trying to assign all values to the results variable and then push it to the state.
When I do console.log(items) it shows all items as well which is very odd.
API data
Any help would be deeply appreciated!
Thanks
javascript arrays json reactjs
So, I'm getting stuck into React and it's already making me scratch my head..
I am grabbing some API data like and trying to access any particular index or loop through - whatever I do, it does not seem to work!
Here is the main component:
class App extends React.Component {
const CityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff'];
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items:
};
}
// Fire our function below on app load
componentDidMount() {
this.getWeather();
}
// getWeather - make api call
getWeather = () => {
let results = ;
// Loop through our cities list here to gather data
// We will then push this into this.state.results
CityListNames.forEach(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
// get api data
fetch(api_url)
.then(res => res.json())
.then(
(result) => {
results.push(result);
console.log(result[0]);
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
});
this.setState({
isLoaded: true,
items: results
});
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
When I use console.log(result[0]);
it simply outputs as "undefined" in the console.
I am trying to assign all values to the results variable and then push it to the state.
When I do console.log(items) it shows all items as well which is very odd.
API data
Any help would be deeply appreciated!
Thanks
javascript arrays json reactjs
javascript arrays json reactjs
edited Nov 19 '18 at 21:04
Nathan Fitzgerald - Fitzgenius
asked Nov 19 '18 at 20:59
Nathan Fitzgerald - FitzgeniusNathan Fitzgerald - Fitzgenius
3731735
3731735
2
fetch()
is asynchronous. What you see in console is not a snapshot. It will represent updates even after it is logged
– charlietfl
Nov 19 '18 at 21:04
2
Possible duplicate of How do I return the response from an asynchronous call?
– hindmost
Nov 19 '18 at 21:06
Do not post images of code or errors! Images and screenshots can be a nice addition to a post, but please make sure the post is still cle ar and useful without them. If you post images of code or error messages make sure you also copy and paste or type the actual code/message into the post directly.
– Rob
Nov 20 '18 at 2:09
add a comment |
2
fetch()
is asynchronous. What you see in console is not a snapshot. It will represent updates even after it is logged
– charlietfl
Nov 19 '18 at 21:04
2
Possible duplicate of How do I return the response from an asynchronous call?
– hindmost
Nov 19 '18 at 21:06
Do not post images of code or errors! Images and screenshots can be a nice addition to a post, but please make sure the post is still cle ar and useful without them. If you post images of code or error messages make sure you also copy and paste or type the actual code/message into the post directly.
– Rob
Nov 20 '18 at 2:09
2
2
fetch()
is asynchronous. What you see in console is not a snapshot. It will represent updates even after it is logged– charlietfl
Nov 19 '18 at 21:04
fetch()
is asynchronous. What you see in console is not a snapshot. It will represent updates even after it is logged– charlietfl
Nov 19 '18 at 21:04
2
2
Possible duplicate of How do I return the response from an asynchronous call?
– hindmost
Nov 19 '18 at 21:06
Possible duplicate of How do I return the response from an asynchronous call?
– hindmost
Nov 19 '18 at 21:06
Do not post images of code or errors! Images and screenshots can be a nice addition to a post, but please make sure the post is still cle ar and useful without them. If you post images of code or error messages make sure you also copy and paste or type the actual code/message into the post directly.
– Rob
Nov 20 '18 at 2:09
Do not post images of code or errors! Images and screenshots can be a nice addition to a post, but please make sure the post is still cle ar and useful without them. If you post images of code or error messages make sure you also copy and paste or type the actual code/message into the post directly.
– Rob
Nov 20 '18 at 2:09
add a comment |
4 Answers
4
active
oldest
votes
You have to wait for all of your api requests to resolve before setting your state, so instead of using forEach, use map and then return a promise of the date like so:
getWeather = () => {
// Loop through our cities list here to gather data
// We will then push this into this.state.results
Promise.all(CityListNames.map(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
return fetch(api_url)
.then(res => res.json());
})).then((results) => {
this.setState({
isLoaded: true,
items: results
});
}).catch((error) => {
this.setState({
isLoaded: true,
error
});
});
}
Thank you, this has solved my problem!
– Nathan Fitzgerald - Fitzgenius
Nov 19 '18 at 21:14
add a comment |
Try this.
class App extends React.Component {
const CityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff'];
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items:
};
}
// Fire our function below on app load
componentDidMount() {
this.getWeather();
}
// getWeather - make api call
getWeather = () => {
let self = this,
results = , responses = ;
// Loop through our cities list here to gather data
// We will then push this into this.state.results
CityListNames.forEach(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
// get api data
fetch(api_url)
.then(res => {
responses.push(res.json());
});
};
Promise.all(responses).then((values) => {
self.setState({
isLoaded: true,
items: results
});
});// this works, because setState is called after before all promises are fulfilled
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
add a comment |
Did you mean to console.log(results[0]) plural of 'result'. In your promise result is what you get after you parse the response to json. If that response does not have a key of '0' (which it shouldn't), then you will get undefined.
Edit
The issue is not that you are making an asynchronous call and then performing the synchronous action of a push and console.log. The issue is that there is a typo where you are console logging vs pushing the proper response.
fetch(api_url)
.then(res => res.json())
.then(
(result) => {
results.push(result); // <--- pushes valid response into array
console.log(result[0]); // <--- logs undefined
},
The response does not have a key of "0" therefore you log undefined, but you push result (which is valid). Therefore you will get an array of proper results at the end of your calls. But you will log a bunch of "undefined" to console.
add a comment |
1.fetch: works asynchronously, therefore when you assign to the state the value of results this will be an empty array.
this.setState({
isLoaded: true,
items: results
});
the previous code must go in the fetch result
class App extends React.Component {
cityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff']; // this is one of the changes
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items:
};
}
componentDidMount() {
this.getWeather();
}
getWeather = () => {
let results = ;
this.cityListNames.forEach(function (name) { //this is one of the changes
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
fetch(api_url)
.then(res => res.json())
.then((result) => {
results.push(result);
this.setState({ // this is one of the changes
isLoaded: true,
items: results
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
});
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
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%2f53382540%2fcant-access-javascript-object-within-react-component%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
You have to wait for all of your api requests to resolve before setting your state, so instead of using forEach, use map and then return a promise of the date like so:
getWeather = () => {
// Loop through our cities list here to gather data
// We will then push this into this.state.results
Promise.all(CityListNames.map(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
return fetch(api_url)
.then(res => res.json());
})).then((results) => {
this.setState({
isLoaded: true,
items: results
});
}).catch((error) => {
this.setState({
isLoaded: true,
error
});
});
}
Thank you, this has solved my problem!
– Nathan Fitzgerald - Fitzgenius
Nov 19 '18 at 21:14
add a comment |
You have to wait for all of your api requests to resolve before setting your state, so instead of using forEach, use map and then return a promise of the date like so:
getWeather = () => {
// Loop through our cities list here to gather data
// We will then push this into this.state.results
Promise.all(CityListNames.map(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
return fetch(api_url)
.then(res => res.json());
})).then((results) => {
this.setState({
isLoaded: true,
items: results
});
}).catch((error) => {
this.setState({
isLoaded: true,
error
});
});
}
Thank you, this has solved my problem!
– Nathan Fitzgerald - Fitzgenius
Nov 19 '18 at 21:14
add a comment |
You have to wait for all of your api requests to resolve before setting your state, so instead of using forEach, use map and then return a promise of the date like so:
getWeather = () => {
// Loop through our cities list here to gather data
// We will then push this into this.state.results
Promise.all(CityListNames.map(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
return fetch(api_url)
.then(res => res.json());
})).then((results) => {
this.setState({
isLoaded: true,
items: results
});
}).catch((error) => {
this.setState({
isLoaded: true,
error
});
});
}
You have to wait for all of your api requests to resolve before setting your state, so instead of using forEach, use map and then return a promise of the date like so:
getWeather = () => {
// Loop through our cities list here to gather data
// We will then push this into this.state.results
Promise.all(CityListNames.map(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
return fetch(api_url)
.then(res => res.json());
})).then((results) => {
this.setState({
isLoaded: true,
items: results
});
}).catch((error) => {
this.setState({
isLoaded: true,
error
});
});
}
answered Nov 19 '18 at 21:12
dotconnordotconnor
1,062120
1,062120
Thank you, this has solved my problem!
– Nathan Fitzgerald - Fitzgenius
Nov 19 '18 at 21:14
add a comment |
Thank you, this has solved my problem!
– Nathan Fitzgerald - Fitzgenius
Nov 19 '18 at 21:14
Thank you, this has solved my problem!
– Nathan Fitzgerald - Fitzgenius
Nov 19 '18 at 21:14
Thank you, this has solved my problem!
– Nathan Fitzgerald - Fitzgenius
Nov 19 '18 at 21:14
add a comment |
Try this.
class App extends React.Component {
const CityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff'];
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items:
};
}
// Fire our function below on app load
componentDidMount() {
this.getWeather();
}
// getWeather - make api call
getWeather = () => {
let self = this,
results = , responses = ;
// Loop through our cities list here to gather data
// We will then push this into this.state.results
CityListNames.forEach(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
// get api data
fetch(api_url)
.then(res => {
responses.push(res.json());
});
};
Promise.all(responses).then((values) => {
self.setState({
isLoaded: true,
items: results
});
});// this works, because setState is called after before all promises are fulfilled
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
add a comment |
Try this.
class App extends React.Component {
const CityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff'];
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items:
};
}
// Fire our function below on app load
componentDidMount() {
this.getWeather();
}
// getWeather - make api call
getWeather = () => {
let self = this,
results = , responses = ;
// Loop through our cities list here to gather data
// We will then push this into this.state.results
CityListNames.forEach(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
// get api data
fetch(api_url)
.then(res => {
responses.push(res.json());
});
};
Promise.all(responses).then((values) => {
self.setState({
isLoaded: true,
items: results
});
});// this works, because setState is called after before all promises are fulfilled
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
add a comment |
Try this.
class App extends React.Component {
const CityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff'];
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items:
};
}
// Fire our function below on app load
componentDidMount() {
this.getWeather();
}
// getWeather - make api call
getWeather = () => {
let self = this,
results = , responses = ;
// Loop through our cities list here to gather data
// We will then push this into this.state.results
CityListNames.forEach(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
// get api data
fetch(api_url)
.then(res => {
responses.push(res.json());
});
};
Promise.all(responses).then((values) => {
self.setState({
isLoaded: true,
items: results
});
});// this works, because setState is called after before all promises are fulfilled
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
Try this.
class App extends React.Component {
const CityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff'];
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items:
};
}
// Fire our function below on app load
componentDidMount() {
this.getWeather();
}
// getWeather - make api call
getWeather = () => {
let self = this,
results = , responses = ;
// Loop through our cities list here to gather data
// We will then push this into this.state.results
CityListNames.forEach(function (name) {
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
// get api data
fetch(api_url)
.then(res => {
responses.push(res.json());
});
};
Promise.all(responses).then((values) => {
self.setState({
isLoaded: true,
items: results
});
});// this works, because setState is called after before all promises are fulfilled
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
answered Nov 19 '18 at 21:34
TuringCreepTuringCreep
365
365
add a comment |
add a comment |
Did you mean to console.log(results[0]) plural of 'result'. In your promise result is what you get after you parse the response to json. If that response does not have a key of '0' (which it shouldn't), then you will get undefined.
Edit
The issue is not that you are making an asynchronous call and then performing the synchronous action of a push and console.log. The issue is that there is a typo where you are console logging vs pushing the proper response.
fetch(api_url)
.then(res => res.json())
.then(
(result) => {
results.push(result); // <--- pushes valid response into array
console.log(result[0]); // <--- logs undefined
},
The response does not have a key of "0" therefore you log undefined, but you push result (which is valid). Therefore you will get an array of proper results at the end of your calls. But you will log a bunch of "undefined" to console.
add a comment |
Did you mean to console.log(results[0]) plural of 'result'. In your promise result is what you get after you parse the response to json. If that response does not have a key of '0' (which it shouldn't), then you will get undefined.
Edit
The issue is not that you are making an asynchronous call and then performing the synchronous action of a push and console.log. The issue is that there is a typo where you are console logging vs pushing the proper response.
fetch(api_url)
.then(res => res.json())
.then(
(result) => {
results.push(result); // <--- pushes valid response into array
console.log(result[0]); // <--- logs undefined
},
The response does not have a key of "0" therefore you log undefined, but you push result (which is valid). Therefore you will get an array of proper results at the end of your calls. But you will log a bunch of "undefined" to console.
add a comment |
Did you mean to console.log(results[0]) plural of 'result'. In your promise result is what you get after you parse the response to json. If that response does not have a key of '0' (which it shouldn't), then you will get undefined.
Edit
The issue is not that you are making an asynchronous call and then performing the synchronous action of a push and console.log. The issue is that there is a typo where you are console logging vs pushing the proper response.
fetch(api_url)
.then(res => res.json())
.then(
(result) => {
results.push(result); // <--- pushes valid response into array
console.log(result[0]); // <--- logs undefined
},
The response does not have a key of "0" therefore you log undefined, but you push result (which is valid). Therefore you will get an array of proper results at the end of your calls. But you will log a bunch of "undefined" to console.
Did you mean to console.log(results[0]) plural of 'result'. In your promise result is what you get after you parse the response to json. If that response does not have a key of '0' (which it shouldn't), then you will get undefined.
Edit
The issue is not that you are making an asynchronous call and then performing the synchronous action of a push and console.log. The issue is that there is a typo where you are console logging vs pushing the proper response.
fetch(api_url)
.then(res => res.json())
.then(
(result) => {
results.push(result); // <--- pushes valid response into array
console.log(result[0]); // <--- logs undefined
},
The response does not have a key of "0" therefore you log undefined, but you push result (which is valid). Therefore you will get an array of proper results at the end of your calls. But you will log a bunch of "undefined" to console.
edited Nov 20 '18 at 15:25
answered Nov 19 '18 at 21:05
Sunny WongSunny Wong
866
866
add a comment |
add a comment |
1.fetch: works asynchronously, therefore when you assign to the state the value of results this will be an empty array.
this.setState({
isLoaded: true,
items: results
});
the previous code must go in the fetch result
class App extends React.Component {
cityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff']; // this is one of the changes
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items:
};
}
componentDidMount() {
this.getWeather();
}
getWeather = () => {
let results = ;
this.cityListNames.forEach(function (name) { //this is one of the changes
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
fetch(api_url)
.then(res => res.json())
.then((result) => {
results.push(result);
this.setState({ // this is one of the changes
isLoaded: true,
items: results
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
});
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
add a comment |
1.fetch: works asynchronously, therefore when you assign to the state the value of results this will be an empty array.
this.setState({
isLoaded: true,
items: results
});
the previous code must go in the fetch result
class App extends React.Component {
cityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff']; // this is one of the changes
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items:
};
}
componentDidMount() {
this.getWeather();
}
getWeather = () => {
let results = ;
this.cityListNames.forEach(function (name) { //this is one of the changes
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
fetch(api_url)
.then(res => res.json())
.then((result) => {
results.push(result);
this.setState({ // this is one of the changes
isLoaded: true,
items: results
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
});
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
add a comment |
1.fetch: works asynchronously, therefore when you assign to the state the value of results this will be an empty array.
this.setState({
isLoaded: true,
items: results
});
the previous code must go in the fetch result
class App extends React.Component {
cityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff']; // this is one of the changes
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items:
};
}
componentDidMount() {
this.getWeather();
}
getWeather = () => {
let results = ;
this.cityListNames.forEach(function (name) { //this is one of the changes
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
fetch(api_url)
.then(res => res.json())
.then((result) => {
results.push(result);
this.setState({ // this is one of the changes
isLoaded: true,
items: results
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
});
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
1.fetch: works asynchronously, therefore when you assign to the state the value of results this will be an empty array.
this.setState({
isLoaded: true,
items: results
});
the previous code must go in the fetch result
class App extends React.Component {
cityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff']; // this is one of the changes
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items:
};
}
componentDidMount() {
this.getWeather();
}
getWeather = () => {
let results = ;
this.cityListNames.forEach(function (name) { //this is one of the changes
let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
let data;
fetch(api_url)
.then(res => res.json())
.then((result) => {
results.push(result);
this.setState({ // this is one of the changes
isLoaded: true,
items: results
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
});
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="weather-app">
</div>
);
}
}
}
export default App;
edited Nov 19 '18 at 21:26
answered Nov 19 '18 at 21:21
Juan Esteban Londoño TabaresJuan Esteban Londoño Tabares
327212
327212
add a comment |
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%2f53382540%2fcant-access-javascript-object-within-react-component%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
2
fetch()
is asynchronous. What you see in console is not a snapshot. It will represent updates even after it is logged– charlietfl
Nov 19 '18 at 21:04
2
Possible duplicate of How do I return the response from an asynchronous call?
– hindmost
Nov 19 '18 at 21:06
Do not post images of code or errors! Images and screenshots can be a nice addition to a post, but please make sure the post is still cle ar and useful without them. If you post images of code or error messages make sure you also copy and paste or type the actual code/message into the post directly.
– Rob
Nov 20 '18 at 2:09