Handling api calls in Redux with Axios
axios
is the promise so you need to use then
to get your result. You should request your api in a separate file and call your action when the result comes back.
//WebAPIUtil.jsaxios.get('http://localhost:3000/flug') .then(function(result){ YourAction.getAllFlights(result) });
In your action file will be like this :
export function getAllFlights(request) { console.log(request); return { type: FETCH_FLIGHT, payload: request };}
You can do this with thunk. https://github.com/gaearon/redux-thunk
You can dispatch an action in your then
and it will update state when it gets a response from the axios call.
export function someFunction() { return(dispatch) => { axios.get(URL) .then((response) => {dispatch(YourAction(response));}) .catch((response) => {return Promise.reject(response);}); };}
I also think the best way to do this is by redux-axios-middleware. The setup can be a bit tricky as your store should be configured in a similar way:
import { createStore, applyMiddleware } from 'redux';import axiosMiddleware from 'redux-axios-middleware';import axios from 'axios';import rootReducer from '../reducers';const configureStore = () => { return createStore( rootReducer, applyMiddleware(axiosMiddleware(axios)) );}const store = configureStore();
And your action creators now look like this:
import './axios' // that's your axios.js file, not the libraryexport const FETCH_FLIGHT = 'FETCH_FLIGHT';export const getAllFlights = () => { return { type: FETCH_FLIGHT, payload: { request: { method: 'post', // or get url:'http://localhost:3000/flug' } } }}