Read: Class 38 Redux Asynchronous Actions - 401-advanced-javascript-muna/amman-javascript-401d1 GitHub Wiki

Redux - Asynchronous Actions

Thunking for Data…

Using Redux actions to connect to remote APIs via Thunk Middleware

Normally, action generators return a function, like this: const get = (payload) => { return { type: 'GET', payload: payload } }

But often, you’ll need your actions to do some asynchronous action before you dispatch it to the reducer. For example, you may need to get something from a remote api.

In this case, we want to set it up like this, where the action you dispatch from your React App returns a function, not an actual action object, which is what Redux expects and requires

`let api = 'https://api.mockable.io/api/v1/stuff';

export const get = () => dispatch => { return utils.fetchData(api).then(records => { dispatch(getAction(records)); }); };

const getAction = payload => { return { type: 'GET', payload: payload, }; };`

So, we will implement special redux middleware, called “thunk”, which inspects every dispatched action and then either lets it go through (in the case of a normal action that returns an object) or it processes the function and then dispatches what that function returns.

Notice in the example above, that the function we ran for the action is curried, and receives dispatch(), which it calls with the payload it got from the server.