I ma trying to show part of an APi response but it keeps giving me undefined when i try to parse it.
I have tried doing 2 parts of the API response but neither work.
class App extends Component {
constructor() {
super();
this.state = {
head: 0,
data: [],
firstName: "Brad",
lastName: "Marchand",
err: null
};
}
componentDidMount() {
axios
.get("http://localhost:3001/api/player", {
params: {
firstName: this.state.firstName,
lastName: this.state.lastName
}
})
.then(response => {
this.setState({
data: response.data
});
console.log(this.state.data);
})
.catch(err => {
//this.err = err;
});
}
render() {
return (
<>
<p>{this.state.data.players[0].player.firstName}</p>
<p>Hello</p>
</>
);
}
}
backend
request(options, (err, response, body) => {
if (err) {
signale.error(err);
}
var data = JSON.parse(body);
//var data = JSON.stringify(data.players);
//var data = JSON.parse(data);
signale.success(data);
res.send(data);
});
{ lastUpdatedOn: '2019-08-15T15:20:13.791Z',
[0] players: [ { player: [Object], teamAsOfDate: [Object] } ],
[0] references: { teamReferences: [ [Object] ], venueReferences: [ [Object] ] } }
Another expected response Another response
Trying to just output what i want from the response but always get undefined past this.state.data
So the issue here is that you are making an API call in componentDidMount and the response of the API will definitely come after the initial render, and in the initial render, this.state.data.players[0].player.firstName
is undefined and it breaks your code. Add a conditional check before accessing the value. Also initialise data
state as an object if its one
class App extends Component {
constructor() {
super();
this.state = {
head: 0,
data: {},
firstName: "Brad",
lastName: "Marchand",
err: null
};
}
componentDidMount() {
axios
.get("http://localhost:3001/api/player", {
params: {
firstName: this.state.firstName,
lastName: this.state.lastName
}
})
.then(response => {
this.setState({
data: response.data
});
console.log(this.state.data);
})
.catch(err => {
//this.err = err;
});
}
render() {
return (
<>
<p>{this.state.data.players && this.state.data.players[0].player.firstName}</p>
<p>Hello</p>
</>
);
}
}
React setState() works asynchronously, which means there is a slight delay in setting the value in the state. You can passing in a callback to setState() which is called once the state is updated.
this.setState({
data: response.data
}, () => { console.log(this.state.data); });
Cheers,
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.