How to use axios / AJAX with redux-thunk How to use axios / AJAX with redux-thunk reactjs reactjs

How to use axios / AJAX with redux-thunk


I guess you shouldn't (or at least not supposed to) put the promise directly at the store:

export function FetchWeather(city) {  let url = `${API_URL}&q=${city},in`;  let promise = axios.get(url);  return {    type: types.FETCH_WEATHER,    payload: promise  };}

This way you are not even using redux-thunk, because it's returning a plain object. Actually, redux-thunk, enables you to return a function that will be evaluated later, for example, something like this:

export function FetchWeather(city) {  let url = `${API_URL}&q=${city},in`;  return function (dispatch) {     axios.get(url)      .then((response) => dispatch({        type: types.FETCH_WEATHER_SUCCESS,        data: response.data      })).catch((response) => dispatch({        type: types.FETCH_WEATHER_FAILURE,        error: response.error      }))  }}

Be sure to properly setup the redux-thunk middleware. I really recommend reading redux-thunk documentation and this amazing article to have a deeper understanding.