Reputation: 252
I'm currently using functions to predefine all of my axios calls so for example:
export const getClients = () => {
axios.get("/client/")
.then(response=>{
return response;
})
.catch(error=>{
return error;
});
};
Now, I want to call this in a class-based component in the componentDidMount
like this:
componentDidMount(){
this.setState({
clients: getClients()
});
}
I can't seem to figure out why when I try to console.log(this.state.clients)
at the end of componentDidMount
I'm getting an undefined error. I'm new to React and from what I understand, the then
in the function of the axios call should resolve the promise and return the actual response from the API call so when I call getClients()
, the clients
state should be the response.
What am I doing wrong?
Upvotes: 1
Views: 1484
Reputation: 1036
componentDidMount(){
fetchClients();
}
const fetchClients = () => {
getClients().then( (response)=> {
// handle success
this.setState({clients:response});
});
};
Upvotes: 1
Reputation: 8316
Okay there is some stuff that needs to be cleared out here :-
getClients
like so :-export const getClients = () => {
return axios.get("/client/")
.then(response=>{
return response;
})
.catch(error=>{
return error;
});
};
Why ?
Because the value that you returned from the callback of then
is wrapped inside a Promise implicitly and has to be returned for consumption as you do in a function like function sum(a,b) {return a+b}
componentDidMount
will change like so :-componentDidMount(){
const fetchClients = async () => {
const clients = await getClients();
this.setState({clients});
}
fetchClients();
}
Why ?
If you want to use getClients
in a statement fashion instead of .then().then()
promise chain, you will first wrap it inside an async
function and then call await
on getClients()
(remember this function returns a Promise
) and then set the state inside that async function.
console.log
the clients
state after fetchClients()
within componentDidMount
, you probably won't see the value set because setState
works asynchronously. So never rely on the console.log
of your state just after setting it.Upvotes: 1