React/FetchAPI: How to take data from related json by id
I want to take data from JSON, next take another data from related JSON by ID and push it to my state array movies
.
This is my code:
state = {
movies:
}
componentDidMount() {
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(data => {
const movies = data.results;
movies.forEach(movie => this.moviePageAndGenres(movie.id, movie));
this.setState({
movies
});
})
}
moviePageAndGenres = (id, element) => {
fetch('https://api.themoviedb.org/3/movie/' + id + '?api_key=APIKEY')
.then(response => response.json())
.then(data => {
element.genres = data.genres;
element.homepage = data.homepage;
});
}
In render()
I just console.log
my movies
to check if data inside is correct.
Output:
image
So it's correct but when I check Component Props these props are not transferred.
image
This is how I transfer props:
const movies = this.state.movies.map(movie =>
<Movie genres={movie.genres}
homepage={movie.homepage}
key={movie.id}
title={movie.title}
poster={movie.poster_path}
rating={movie.vote_average}
/>
)
I guess it's problem with multiple call of asynchronousfetch()
. But i don't know how to handle with it.
javascript reactjs fetch-api
add a comment |
I want to take data from JSON, next take another data from related JSON by ID and push it to my state array movies
.
This is my code:
state = {
movies:
}
componentDidMount() {
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(data => {
const movies = data.results;
movies.forEach(movie => this.moviePageAndGenres(movie.id, movie));
this.setState({
movies
});
})
}
moviePageAndGenres = (id, element) => {
fetch('https://api.themoviedb.org/3/movie/' + id + '?api_key=APIKEY')
.then(response => response.json())
.then(data => {
element.genres = data.genres;
element.homepage = data.homepage;
});
}
In render()
I just console.log
my movies
to check if data inside is correct.
Output:
image
So it's correct but when I check Component Props these props are not transferred.
image
This is how I transfer props:
const movies = this.state.movies.map(movie =>
<Movie genres={movie.genres}
homepage={movie.homepage}
key={movie.id}
title={movie.title}
poster={movie.poster_path}
rating={movie.vote_average}
/>
)
I guess it's problem with multiple call of asynchronousfetch()
. But i don't know how to handle with it.
javascript reactjs fetch-api
please hide your api key
– sdkcy
Jan 19 at 16:14
this.setState will not wait for your moviePageAndGenres to respond.
– Manish Jangir
Jan 19 at 16:16
you can try to use async functions
– Pommesloch
Jan 19 at 16:24
add a comment |
I want to take data from JSON, next take another data from related JSON by ID and push it to my state array movies
.
This is my code:
state = {
movies:
}
componentDidMount() {
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(data => {
const movies = data.results;
movies.forEach(movie => this.moviePageAndGenres(movie.id, movie));
this.setState({
movies
});
})
}
moviePageAndGenres = (id, element) => {
fetch('https://api.themoviedb.org/3/movie/' + id + '?api_key=APIKEY')
.then(response => response.json())
.then(data => {
element.genres = data.genres;
element.homepage = data.homepage;
});
}
In render()
I just console.log
my movies
to check if data inside is correct.
Output:
image
So it's correct but when I check Component Props these props are not transferred.
image
This is how I transfer props:
const movies = this.state.movies.map(movie =>
<Movie genres={movie.genres}
homepage={movie.homepage}
key={movie.id}
title={movie.title}
poster={movie.poster_path}
rating={movie.vote_average}
/>
)
I guess it's problem with multiple call of asynchronousfetch()
. But i don't know how to handle with it.
javascript reactjs fetch-api
I want to take data from JSON, next take another data from related JSON by ID and push it to my state array movies
.
This is my code:
state = {
movies:
}
componentDidMount() {
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(data => {
const movies = data.results;
movies.forEach(movie => this.moviePageAndGenres(movie.id, movie));
this.setState({
movies
});
})
}
moviePageAndGenres = (id, element) => {
fetch('https://api.themoviedb.org/3/movie/' + id + '?api_key=APIKEY')
.then(response => response.json())
.then(data => {
element.genres = data.genres;
element.homepage = data.homepage;
});
}
In render()
I just console.log
my movies
to check if data inside is correct.
Output:
image
So it's correct but when I check Component Props these props are not transferred.
image
This is how I transfer props:
const movies = this.state.movies.map(movie =>
<Movie genres={movie.genres}
homepage={movie.homepage}
key={movie.id}
title={movie.title}
poster={movie.poster_path}
rating={movie.vote_average}
/>
)
I guess it's problem with multiple call of asynchronousfetch()
. But i don't know how to handle with it.
javascript reactjs fetch-api
javascript reactjs fetch-api
edited Jan 19 at 16:25
zyng9
asked Jan 19 at 16:10
zyng9zyng9
84
84
please hide your api key
– sdkcy
Jan 19 at 16:14
this.setState will not wait for your moviePageAndGenres to respond.
– Manish Jangir
Jan 19 at 16:16
you can try to use async functions
– Pommesloch
Jan 19 at 16:24
add a comment |
please hide your api key
– sdkcy
Jan 19 at 16:14
this.setState will not wait for your moviePageAndGenres to respond.
– Manish Jangir
Jan 19 at 16:16
you can try to use async functions
– Pommesloch
Jan 19 at 16:24
please hide your api key
– sdkcy
Jan 19 at 16:14
please hide your api key
– sdkcy
Jan 19 at 16:14
this.setState will not wait for your moviePageAndGenres to respond.
– Manish Jangir
Jan 19 at 16:16
this.setState will not wait for your moviePageAndGenres to respond.
– Manish Jangir
Jan 19 at 16:16
you can try to use async functions
– Pommesloch
Jan 19 at 16:24
you can try to use async functions
– Pommesloch
Jan 19 at 16:24
add a comment |
2 Answers
2
active
oldest
votes
The reason its not working is, you are firing multiple fetch calls which are async and setting the state immediately after it. setState
will get empty movies in that case.
fetch
api returns a promise and you should set your state in promise resolution handler. Modify your componentDidMount
like this.
componentDidMount() {
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(data => {
const movies = data.results;
Promise.all(movies.map(movie => fetch(
`https://api.themoviedb.org/3/movie/${movie.id}?api_key=APIKEY`
)))
.then(resp => Promise.all( resp.map(r => r.json()) ))
.then(result => {
const movies = result.map((data, i) => {
const movie = Object.assign(movies[i], {
genres: data.genres,
homepage: data.homepage
});
return movie;
});
this.setState({
movies
});
});
})
}
add a comment |
You need async await in this case and it’s good to use Promise.all because you are doing fetch in forEach.
For forEach you need await Promise.all and for fetch you need await. Which mean it will wait until the forEach is completed
Change
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(data => {
const movies = data.results;
movies.forEach(movie => this.moviePageAndGenres(movie.id, movie));
this.setState({
movies
});
})
To
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(async data => {
const movies = data.results;
await Promise.all(movies.forEach(async movie => await this.moviePageAndGenres(movie.id, movie)))
this.setState({
movies
});
})
Also
Change
moviePageAndGenres = (id, element) => {
fetch('https://api.themoviedb.org/3/movie/' + id + '?api_key=APIKEY')
.then(response => response.json())
.then(data => {
element.genres = data.genres;
element.homepage = data.homepage;
});
}
To
moviePageAndGenres = async (id, element) => {
return await fetch('https://api.themoviedb.org/3/movie/' + id + '?api_key=APIKEY')
.then(response => response.json())
.then(data => {
element.genres = data.genres;
element.homepage = data.homepage;
});
}
1
correct me if I'm wrong, I think OP might also need to modifymoviePageAndGenres()
so that it return a promise (simply by returningfetch(...)
)
– Derek Nguyen
Jan 19 at 16:32
Yes you are right. I have updated my answer please let me know if that’s the right approach
– Hemadri Dasari
Jan 19 at 16:35
Updated the code with return :)
– Hemadri Dasari
Jan 19 at 16:40
Sorry, i was on mobile so my finger slips — please disregard the last (removed) comment!
– Derek Nguyen
Jan 19 at 16:41
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%2f54268951%2freact-fetchapi-how-to-take-data-from-related-json-by-id%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
The reason its not working is, you are firing multiple fetch calls which are async and setting the state immediately after it. setState
will get empty movies in that case.
fetch
api returns a promise and you should set your state in promise resolution handler. Modify your componentDidMount
like this.
componentDidMount() {
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(data => {
const movies = data.results;
Promise.all(movies.map(movie => fetch(
`https://api.themoviedb.org/3/movie/${movie.id}?api_key=APIKEY`
)))
.then(resp => Promise.all( resp.map(r => r.json()) ))
.then(result => {
const movies = result.map((data, i) => {
const movie = Object.assign(movies[i], {
genres: data.genres,
homepage: data.homepage
});
return movie;
});
this.setState({
movies
});
});
})
}
add a comment |
The reason its not working is, you are firing multiple fetch calls which are async and setting the state immediately after it. setState
will get empty movies in that case.
fetch
api returns a promise and you should set your state in promise resolution handler. Modify your componentDidMount
like this.
componentDidMount() {
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(data => {
const movies = data.results;
Promise.all(movies.map(movie => fetch(
`https://api.themoviedb.org/3/movie/${movie.id}?api_key=APIKEY`
)))
.then(resp => Promise.all( resp.map(r => r.json()) ))
.then(result => {
const movies = result.map((data, i) => {
const movie = Object.assign(movies[i], {
genres: data.genres,
homepage: data.homepage
});
return movie;
});
this.setState({
movies
});
});
})
}
add a comment |
The reason its not working is, you are firing multiple fetch calls which are async and setting the state immediately after it. setState
will get empty movies in that case.
fetch
api returns a promise and you should set your state in promise resolution handler. Modify your componentDidMount
like this.
componentDidMount() {
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(data => {
const movies = data.results;
Promise.all(movies.map(movie => fetch(
`https://api.themoviedb.org/3/movie/${movie.id}?api_key=APIKEY`
)))
.then(resp => Promise.all( resp.map(r => r.json()) ))
.then(result => {
const movies = result.map((data, i) => {
const movie = Object.assign(movies[i], {
genres: data.genres,
homepage: data.homepage
});
return movie;
});
this.setState({
movies
});
});
})
}
The reason its not working is, you are firing multiple fetch calls which are async and setting the state immediately after it. setState
will get empty movies in that case.
fetch
api returns a promise and you should set your state in promise resolution handler. Modify your componentDidMount
like this.
componentDidMount() {
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(data => {
const movies = data.results;
Promise.all(movies.map(movie => fetch(
`https://api.themoviedb.org/3/movie/${movie.id}?api_key=APIKEY`
)))
.then(resp => Promise.all( resp.map(r => r.json()) ))
.then(result => {
const movies = result.map((data, i) => {
const movie = Object.assign(movies[i], {
genres: data.genres,
homepage: data.homepage
});
return movie;
});
this.setState({
movies
});
});
})
}
edited Jan 20 at 14:11
zyng9
84
84
answered Jan 19 at 16:34
Manish JangirManish Jangir
3,34742342
3,34742342
add a comment |
add a comment |
You need async await in this case and it’s good to use Promise.all because you are doing fetch in forEach.
For forEach you need await Promise.all and for fetch you need await. Which mean it will wait until the forEach is completed
Change
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(data => {
const movies = data.results;
movies.forEach(movie => this.moviePageAndGenres(movie.id, movie));
this.setState({
movies
});
})
To
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(async data => {
const movies = data.results;
await Promise.all(movies.forEach(async movie => await this.moviePageAndGenres(movie.id, movie)))
this.setState({
movies
});
})
Also
Change
moviePageAndGenres = (id, element) => {
fetch('https://api.themoviedb.org/3/movie/' + id + '?api_key=APIKEY')
.then(response => response.json())
.then(data => {
element.genres = data.genres;
element.homepage = data.homepage;
});
}
To
moviePageAndGenres = async (id, element) => {
return await fetch('https://api.themoviedb.org/3/movie/' + id + '?api_key=APIKEY')
.then(response => response.json())
.then(data => {
element.genres = data.genres;
element.homepage = data.homepage;
});
}
1
correct me if I'm wrong, I think OP might also need to modifymoviePageAndGenres()
so that it return a promise (simply by returningfetch(...)
)
– Derek Nguyen
Jan 19 at 16:32
Yes you are right. I have updated my answer please let me know if that’s the right approach
– Hemadri Dasari
Jan 19 at 16:35
Updated the code with return :)
– Hemadri Dasari
Jan 19 at 16:40
Sorry, i was on mobile so my finger slips — please disregard the last (removed) comment!
– Derek Nguyen
Jan 19 at 16:41
add a comment |
You need async await in this case and it’s good to use Promise.all because you are doing fetch in forEach.
For forEach you need await Promise.all and for fetch you need await. Which mean it will wait until the forEach is completed
Change
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(data => {
const movies = data.results;
movies.forEach(movie => this.moviePageAndGenres(movie.id, movie));
this.setState({
movies
});
})
To
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(async data => {
const movies = data.results;
await Promise.all(movies.forEach(async movie => await this.moviePageAndGenres(movie.id, movie)))
this.setState({
movies
});
})
Also
Change
moviePageAndGenres = (id, element) => {
fetch('https://api.themoviedb.org/3/movie/' + id + '?api_key=APIKEY')
.then(response => response.json())
.then(data => {
element.genres = data.genres;
element.homepage = data.homepage;
});
}
To
moviePageAndGenres = async (id, element) => {
return await fetch('https://api.themoviedb.org/3/movie/' + id + '?api_key=APIKEY')
.then(response => response.json())
.then(data => {
element.genres = data.genres;
element.homepage = data.homepage;
});
}
1
correct me if I'm wrong, I think OP might also need to modifymoviePageAndGenres()
so that it return a promise (simply by returningfetch(...)
)
– Derek Nguyen
Jan 19 at 16:32
Yes you are right. I have updated my answer please let me know if that’s the right approach
– Hemadri Dasari
Jan 19 at 16:35
Updated the code with return :)
– Hemadri Dasari
Jan 19 at 16:40
Sorry, i was on mobile so my finger slips — please disregard the last (removed) comment!
– Derek Nguyen
Jan 19 at 16:41
add a comment |
You need async await in this case and it’s good to use Promise.all because you are doing fetch in forEach.
For forEach you need await Promise.all and for fetch you need await. Which mean it will wait until the forEach is completed
Change
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(data => {
const movies = data.results;
movies.forEach(movie => this.moviePageAndGenres(movie.id, movie));
this.setState({
movies
});
})
To
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(async data => {
const movies = data.results;
await Promise.all(movies.forEach(async movie => await this.moviePageAndGenres(movie.id, movie)))
this.setState({
movies
});
})
Also
Change
moviePageAndGenres = (id, element) => {
fetch('https://api.themoviedb.org/3/movie/' + id + '?api_key=APIKEY')
.then(response => response.json())
.then(data => {
element.genres = data.genres;
element.homepage = data.homepage;
});
}
To
moviePageAndGenres = async (id, element) => {
return await fetch('https://api.themoviedb.org/3/movie/' + id + '?api_key=APIKEY')
.then(response => response.json())
.then(data => {
element.genres = data.genres;
element.homepage = data.homepage;
});
}
You need async await in this case and it’s good to use Promise.all because you are doing fetch in forEach.
For forEach you need await Promise.all and for fetch you need await. Which mean it will wait until the forEach is completed
Change
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(data => {
const movies = data.results;
movies.forEach(movie => this.moviePageAndGenres(movie.id, movie));
this.setState({
movies
});
})
To
fetch('https://api.themoviedb.org/3/movie/popular?api_key=APIKEY&page=1')
.then(response => response.json())
.then(async data => {
const movies = data.results;
await Promise.all(movies.forEach(async movie => await this.moviePageAndGenres(movie.id, movie)))
this.setState({
movies
});
})
Also
Change
moviePageAndGenres = (id, element) => {
fetch('https://api.themoviedb.org/3/movie/' + id + '?api_key=APIKEY')
.then(response => response.json())
.then(data => {
element.genres = data.genres;
element.homepage = data.homepage;
});
}
To
moviePageAndGenres = async (id, element) => {
return await fetch('https://api.themoviedb.org/3/movie/' + id + '?api_key=APIKEY')
.then(response => response.json())
.then(data => {
element.genres = data.genres;
element.homepage = data.homepage;
});
}
edited Jan 19 at 16:39
answered Jan 19 at 16:25
Hemadri DasariHemadri Dasari
8,72211440
8,72211440
1
correct me if I'm wrong, I think OP might also need to modifymoviePageAndGenres()
so that it return a promise (simply by returningfetch(...)
)
– Derek Nguyen
Jan 19 at 16:32
Yes you are right. I have updated my answer please let me know if that’s the right approach
– Hemadri Dasari
Jan 19 at 16:35
Updated the code with return :)
– Hemadri Dasari
Jan 19 at 16:40
Sorry, i was on mobile so my finger slips — please disregard the last (removed) comment!
– Derek Nguyen
Jan 19 at 16:41
add a comment |
1
correct me if I'm wrong, I think OP might also need to modifymoviePageAndGenres()
so that it return a promise (simply by returningfetch(...)
)
– Derek Nguyen
Jan 19 at 16:32
Yes you are right. I have updated my answer please let me know if that’s the right approach
– Hemadri Dasari
Jan 19 at 16:35
Updated the code with return :)
– Hemadri Dasari
Jan 19 at 16:40
Sorry, i was on mobile so my finger slips — please disregard the last (removed) comment!
– Derek Nguyen
Jan 19 at 16:41
1
1
correct me if I'm wrong, I think OP might also need to modify
moviePageAndGenres()
so that it return a promise (simply by returning fetch(...)
)– Derek Nguyen
Jan 19 at 16:32
correct me if I'm wrong, I think OP might also need to modify
moviePageAndGenres()
so that it return a promise (simply by returning fetch(...)
)– Derek Nguyen
Jan 19 at 16:32
Yes you are right. I have updated my answer please let me know if that’s the right approach
– Hemadri Dasari
Jan 19 at 16:35
Yes you are right. I have updated my answer please let me know if that’s the right approach
– Hemadri Dasari
Jan 19 at 16:35
Updated the code with return :)
– Hemadri Dasari
Jan 19 at 16:40
Updated the code with return :)
– Hemadri Dasari
Jan 19 at 16:40
Sorry, i was on mobile so my finger slips — please disregard the last (removed) comment!
– Derek Nguyen
Jan 19 at 16:41
Sorry, i was on mobile so my finger slips — please disregard the last (removed) comment!
– Derek Nguyen
Jan 19 at 16:41
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%2f54268951%2freact-fetchapi-how-to-take-data-from-related-json-by-id%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
please hide your api key
– sdkcy
Jan 19 at 16:14
this.setState will not wait for your moviePageAndGenres to respond.
– Manish Jangir
Jan 19 at 16:16
you can try to use async functions
– Pommesloch
Jan 19 at 16:24