I have two files named actions.js and vip.js. I have declared a function fetchVip in action file and imported it in vip file which will populate text element when screen is loaded. I want to access fetchVip response in vip file but i get undefined like this LOG useeffect undefined. While respone works as expected in action file.My code is below.
Vip File
import {fetchVip} from '../../Store/action';
const Vip = props => {
useEffect(() => {
console.log('useeffect', fetchVip());
}, [fetchVip()]);
action file
export const fetchVip = () => {
axios
.post(`${baseUrl}/get-vips`)
.then(function (response) {
return response.data;
})
.catch(function (error) {
console.log('error', error);
return {type: 'ERROR', payload: error};
});
};
fetchVip does not return anything, so you have to add a return statement here first:
export const fetchVip = () => {
return axios
.post(`${baseUrl}/get-vips`)
or remove the curly braces, then it will return as well.
export const fetchVip = () => axios
.post(`${baseUrl}/get-vips`)
...
return {type: 'ERROR', payload: error};
})
Now it will return a promise. That means that the result will not be there right away, but at some point later in time. Therefore, if you want to use it in the useEffect, you have to await for the result to arrive.
you could to this with the ES6 syntax:
useEffect(() => {
const getVip = async () => {
const vip = await fetchUsers();
console.log(vip)
//now you can do something with it
};
getVip();
}, [fetchVip]);
or the promise-then syntax:
useEffect(() => {
fetchVip().then(result => {
console.log(result);
//do something with the result
})
}, [fetchVip]);
This is wrong btw. remove the (). You want to check for the function here, not the result of the function.
}, [fetchVip()]);