How to use axios / AJAX with redux-thunk

STEEL picture STEEL · Apr 15, 2016 · Viewed 34.1k times · Source

Im using axios inside my action. I need to know if this is the right way to do it or not.

actions/index.js ==>

import axios from 'axios';
import types from './actionTypes'
const APY_KEY = '2925805fa0bcb3f3df21bb0451f0358f';
const API_URL = `http://api.openweathermap.org/data/2.5/forecast?appid=${APY_KEY}`;

export function FetchWeather(city) {
  let url = `${API_URL}&q=${city},in`;
  let promise = axios.get(url);

  return {
    type: types.FETCH_WEATHER,
    payload: promise
  };
}

reducer_weather.js ==>

import actionTypes from '../actions/actionTypes'
export default function ReducerWeather (state = null, action = null) {
  console.log('ReducerWeather ', action, new Date(Date.now()));

  switch (action.type) {
    case actionTypes.FETCH_WEATHER:
          return action.payload;
  }

  return state;
}

and then come combining them inside rootReducer.js ==>

import { combineReducers } from 'redux';
import reducerWeather from './reducers/reducer_weather';

export default combineReducers({
  reducerWeather
});

And finally calling it inside my React container some js file...

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {FetchWeather} from '../redux/actions';

class SearchBar extends Component {
  ...
  return (
    <div>
      ...
    </div>
  );
}
function mapDispatchToProps(dispatch) {
  //Whenever FetchWeather is called the result will be passed
  //to all reducers
  return bindActionCreators({fetchWeather: FetchWeather}, dispatch);
}

export default connect(null, mapDispatchToProps)(SearchBar);

Answer

falsarella picture falsarella · Apr 20, 2016

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.