Return Promise from Axios?
23,663
Axios is promise based, so you don't need to wrap it in Promise, you can do something like this, and axiosInstance.[post|put|get| end etc.] methods will return promise.
export function fetchStorage() {
return function (dispatch) {
return axiosInstant.get('/Storage/Get')
.then(function (response) {
let payload = response.data;
console.log(payload);
dispatch({ type: actions.FETCH_STORAGE, payload: { storages: payload } });
})
.catch(function (error) {
console.log(error);
});
};
}
Author by
chobo2
Updated on July 20, 2022Comments
-
chobo2 almost 2 years
I am wondering how do I return a promise form Axios? I am not sure if I need to use an Interceptors?
I have this code right now
export function fetchStorage() { return function (dispatch) { return new Promise(function(resolve, reject) { if (1 === 1) { resolve('it works!'); } else { reject(':('); } }); }; }
and
this.props.fetchStorage().then(function() { console.log('then'); });
Now say I want to change the fetchStorage to do something via ajax and I would have it like
var instance = axios.create({ baseURL: 'http://localhost:54690/api', timeout: 2000, }); instance.get('/Storage/Get') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
how do I return the promise instead of doing it here?
Edit
Just for clarification why I am doing this I have something like this
componentWillMount() { this.props.setPreLoader(true); this.props.fetchStorage().then(function() { this.props.setPreLoader(false); }); } export function fetchStorage() { return function (dispatch) { return new Promise(function (resolve, reject) { axiosInstant.get('/Storage/Get') .then(function (response) { let payload = response.data; console.log(payload); dispatch({ type: actions.FETCH_STORAGE, payload: { storages: payload } }); }) .catch(function (error) { console.log(error); }); }); }; }
-
chobo2 over 7 yearsAh, thought maybe it had it's own returning for a promise and I did not need to wrap it.
-
Kevin B over 7 years@chobo2 certainly looks like it returns a promise. or, at least a thennable.