Step 2.9
Note: this step doesn't work with the live site on github.io. Clone this repo to try this step out
redux-thunk: side effects inside action creators
Redux Thunk middleware for actions with service calls. The documentation is here:
https://github.com/reduxjs/redux-thunk
Remember those simple little action functions? They're called action creators. These little functions can be charged with super powers to allow asynchronous side effects to happen while creating the messages. Asynchronous side effects include service calls against APIs.
Action creators are a natural place to put service calls. Redux thunk middleware passes in the dispatch() and getState() from the store into the action creators. This allows the action creator itself to dispatch different actions in between async side effects. Combined with the async / await syntax, coding service calls is a cinch!
Most of the time, in a single-page app, we apply optimistic UI updates. We can update the UI before the network call completes so the UI feels more responsive. To
Action Creator with a Thunk
What's a thunk? - it is a wrapper function that returns a function. What does it do? Let's find out!
This action creator just returns an object
function addTodo(label: string) {
return { type: 'addTodo', id: uuid(), label };
}
In order for us to make service calls, we need to super charge this with the power of redux-thunk
function addTodo(label: string) {
return async (dispatch: any, getState: () => Store) => {
const addAction = actions.addTodo(label);
const id = addAction.id;
dispatch(addAction);
await service.add(id, getState().todos[id]);
};
}
Let's make some observations:
- the outer function has the same function signature as the previous one
- it returns a function that has
dispatchandgetStateas parameters - the inner function is
asyncenabled, and can await on "side effects" like asynchronous service calls - this inner function has the ability to dispatch additional actions because it has been passed the
dispatch()function from the store - this inner function also has access to the state tree via
getState()
Exercise
-
open up
exercise/src/service/index.tsand study the signature of the functions to call the service such as theadd()function -
open
exercise/src/actions/index.tsand fill in the missing content insideactionsWithService
- note that the
completeandclearfunctions require you to write your own wrapper function
- open
exercise/src/index.tsxand follow the instructions in the TODO comment to make the app prepopulate with data from the service.