Jak używać axios / AJAX z redux-thunk

Używam axios wewnątrz mojej akcji. Muszę wiedzieć, czy to dobry sposób, czy nie.

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;
}

A następnie połączyć je wewnątrz rootReducer.js ==>

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

export default combineReducers({
  reducerWeather
});

I wreszcie wywołanie go w moim kontenerze Reactowym jakimś plikiem js...

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);
Author: falsarella, 2016-04-15

1 answers

Chyba nie powinieneś (a przynajmniej nie powinieneś) składać obietnicy bezpośrednio w sklepie:

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

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

W ten sposób nie używasz nawet redux-thunk, ponieważ zwraca zwykły obiekt. W rzeczywistości, redux-thunk, umożliwia zwrócenie funkcji, która będzie później oceniana, na przykład, coś takiego:

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
      }))
  }
}

Upewnij się, że poprawnie skonfigurowałeś Redux-thunk middleware. I naprawdę polecam czytanie redux-thunk documentation i to niesamowite Artykuł aby mieć głębsze zrozumienie.

 25
Author: falsarella,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-04 13:34:03