Reputation: 207
I am trying to fetch some data, rework the object format and safe it in state. My last .then
does not get the data from second one. I don't understand why this is the case.
fetch("http://myserver/switches")
.then(response => response.json())
.then(data => {
a = data.map(item => {
var obj = {}
obj = {value: item.switch, label: item.switch}
return obj
})
console.log(a)
})
.then(data => {
console.log(data)
this.setState({ switches: data})
console.log(this.state.switches)
})
console log:
>(5) [{…}, {…}, {…}, {…}, {…}]
>undefined
>undefined
Upvotes: 0
Views: 47
Reputation: 411
Try to add in the second then() a statement return a
This will provide a
as a parameter for the last then().
fetch("http://myserver/switches")
.then(response => response.json())
.then(data => {
a = data.map(item => {
var obj = {}
obj = {value: item.switch, label: item.switch}
return obj
})
console.log(a)
return a;
})
.then(data => {
console.log(data)
this.setState({ switches: data})
console.log(this.state.switches)
})
Upvotes: 1