React Ajax request with axios (Camper Leader Board)

Hi,

I am fetching data by using axios, could someone help me with the following question. Why getLatest1 -function does not work but version number 2? Function 1 does not re-render when data is fetched.

-Zumartic-

componentDidMount() {
this.getLatest();
}

// WRONG
getLatest1(){
this.setState( axios.get(‘https://fcctop100.herokuapp.com/api/fccusers/top/recent’)
.then(function (response) {
return {
userlist: response.data
};
})
.catch(function (error) {
console.log(error);
})
)
}

// CORRECT
getLatest2(){
return axios.get(“https://fcctop100.herokuapp.com/api/fccusers/top/recent”).then(result=> {
this.setState({ userlist: result.data });
})
.catch(err=>{
console.log(“STH WRONG”);
});
}

In the first one, you call setState and then the axios call which is incorrect. You want axios to run and then call setState on the result.