Skip to content

Instantly share code, notes, and snippets.

@zzdjk6
Created July 23, 2019 10:05
Show Gist options
  • Save zzdjk6/030624fd2bfd4572531ebbfeda702676 to your computer and use it in GitHub Desktop.
Save zzdjk6/030624fd2bfd4572531ebbfeda702676 to your computer and use it in GitHub Desktop.
// 1. Define a routine
const FetchDataRoutine: createThunkRoutine<DataType, Error>('FETCH_DATA')
// 2. Create a thunk
const fetchData = () => async (dispatch: Dispatch, getState: () => RootState) => {
dispatch(FetchDataRoutine.request());
try {
const data = await api.fetchData();
dispatch(FetchDataRoutine.success(data));
} catch (e) {
dispatch(FetchDataRoutine.failure(e));
}
}
// 3. Handle actions in reducers
if (action.type === FetchDataRoutine.REQUEST) {
return {
...state,
isFetching: true,
error: null
};
}
if (action.type === FetchDataRoutine.SUCCESS) {
return {
...state,
isFetching: false,
data: action.payload,
error: null
};
}
if (action.type === 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