Skip to content

Fetch Async Data

JP Barbosa edited this page Apr 24, 2018 · 4 revisions
Create env file to store external API path
echo "REACT_APP_API=https://vehicles-finder-api.herokuapp.com" > ./.env.local
Modify vehicles actions to fetch async data from an API
nano ./src/actions/vehicles.js
- import staticData from '../data/vehicles';
+ import axios from 'axios';
import { FETCH_VEHICLES } from './types';

- export const fetchVehicles = () => (
-   {
-     type: FETCH_VEHICLES,
-     payload: staticData.vehicles,
-   }
- );
+ export const fetchVehicles = (params = {}) => (
+   (dispatch) => {
+     axios.get(`${process.env.REACT_APP_API}/vehicles/search`, {
+       params,
+     }).then((response) => {
+       dispatch({
+         type: FETCH_VEHICLES,
+         payload: response.data,
+       });
+     });
+   }
+ );
Add Redux Thunk middleware
nano ./src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
- import { createStore } from 'redux';
+ import { createStore, applyMiddleware } from 'redux';
+ import ReduxThunk from 'redux-thunk';
import { Provider } from 'react-redux';
import reducers from './reducers';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';

- const store = createStore(reducers);
+ const store = createStore(reducers, applyMiddleware(ReduxThunk));
...
Restart the app and open it to check if everything is fine
yarn start
open http://localhost:3000/
Next step: Filters Components