Skip to content

Instantly share code, notes, and snippets.

@zzdjk6
Last active February 13, 2020 09:19
Show Gist options
  • Save zzdjk6/222cec77127f08f66e4d854ed33bd835 to your computer and use it in GitHub Desktop.
Save zzdjk6/222cec77127f08f66e4d854ed33bd835 to your computer and use it in GitHub Desktop.
// 1. Define a routine
const fetchDataRoutine = createThunkRoutine<DataType>('FETCH_DATA');
// Or explicitly decalre the error type if need
// const fetchDataRoutine: createThunkRoutine<DataType, Error>('FETCH_DATA')
// 2. Define the thunk action creator
// Note: We will address the repetitive logic flow later on
const fetchData = (id: number) => async (dispatch: Dispatch) => {
await dispatch(fetchDataRoutine.request(id));
try {
const data = await api.fetchData(id);
return await dispatch(fetchDataRoutine.success(data));
} catch (e) {
await dispatch(fetchDataRoutine.failure(e));
throw e;
}
};
// 3. Handle actions in reducers
switch (action.type) {
case fetchDataRoutine.REQUEST:
return {
...state,
isFetching: true,
error: null
};
case fetchDataRoutine.SUCCESS:
return {
...state,
isFetching: false,
data: action.payload,
error: null
};
case fetchDataRoutine.FAILURE:
return {
...state,
isFetching: false,
error: action.payload
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment