Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  161] [ 4]  / answers: 1 / hits: 17992  / 6 Years ago, mon, july 23, 2018, 12:00:00

I am making an app where I receive data from an API. Once I get this data I want to make another call to the same API with the endpoint that I got from the first call.



fetch(req)
.then((response)=>(
response.json()
)).then((json)=>{
console.log(json)
json.meals.map((obj)=>{
let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
let req = new Request(url,{
method: 'GET',
headers: header
})
fetch(req)
.then((response)=>(
response.json()
)).then((json)=>{
console.log(json);
this.setState((prevState)=>{
recipe: prevState.recipe.push(json)
})
})
})
this.setState(()=>{
return{
data: json
}
})
})


I am making two fetch requests here but the problem is the data from the first response is output after second fetch request. Also the state: data gets set before state: recipe and the components render with the data from state: data.



render(){
return(
<div className=my-container>
<EnterCalorie getData={this.getData}/>
<MealData data={this.state.data} recipe={this.state.recipe}/>
</div>
)
}


How can i make sure both get passed down at the same time?


More From » html

 Answers
5

In line 3 return return response.json() instead of nothing (undefined).



Update:



const toJson = response => response.json()

fetch(req)
.then(toJson)
.then(json => {
this.setState(() => {
return {
data: json
}
})

return json
})
.then((json) => {
console.log(json)
const promises = json.meals.map((obj) => {
let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
let req = new Request(url, {
method: 'GET',
headers: header
})
return fetch(req)
.then(toJson)
.then((json) => {
console.log(json);
this.setState((prevState) => ({
recipe: prevState.recipe.push(json)
}))
})
})

return Promise.all(promises)
})
.then(() => {
console.log('job done')
})


You need to map your array into promises. Then use Promise.all to wait for them the get resolved.



There was parenthesis missing from:



this.setState((prevState)=>{
recipe: prevState.recipe.push(json)
})


A sidenote, this whole stuff should be refactored. You're not going to get far with this code style / code complexity.


[#53906] Thursday, July 19, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
halleyb

Total Points: 604
Total Questions: 96
Total Answers: 115

Location: Tokelau
Member since Wed, Oct 14, 2020
4 Years ago
halleyb questions
;