Reputation: 11
I have a function called get which fetches data from a local rest api
const get = () => {
axios.get(URL).then((response) => {
console.log(response)
return response;
}).catch((error) => {
console.log('ERROR', error)
return error
})
}
Then within App.js i have used the function
useEffect(() =>{
const response = Data.get();
console.log(response)
setPersons(response.data)
}, []);
The console.log(response)
within the get function is returning the rest api data while the useEffect()
is logging undefined
Anybody have any idea why it is not returning the same?
Upvotes: 0
Views: 94
Reputation: 1769
Looks like you're missing a return statement in the get()
function. It should look like this:
const get = () => {
return axios.get(URL).then((response) => {
console.log(response)
return response;
}).catch((error) => {
console.log('ERROR', error)
return error
})
}
That will cause Data.get()
to return the Promise from axios.
You'll then need to wait for the returned Promise to resolve before you can log it from App.js.
You can do that with a .then
:
useEffect(() =>{
Data.get()
.then(response => {
console.log(response)
setPersons(response.data)
});
}, []);
Or an async function:
useEffect(async () =>{
const response = await Data.get();
console.log(response)
setPersons(response.data)
}, []);
Upvotes: 1
Reputation: 2363
The axios request is asynchronous. After you call Data.get
the code continues onto the next line without waiting for the response. You could fix this by allowing your get
function to accept a callback. Something like this:
const get = (success, error) => {
axios.get(URL).then((response) => {
console.log(response)
success(response)
}).catch((e) => {
console.log('ERROR', e)
error(e)
})
}
useEffect(() =>{
Data.get(({data}) => setPersons(data), (error) => console.log(error));
}, []);
Upvotes: 0