Skip to content

Instantly share code, notes, and snippets.

@zzdjk6
Created July 23, 2019 10:04
Show Gist options
  • Save zzdjk6/ed5fe0bacb84167514c2816dbb33a31e to your computer and use it in GitHub Desktop.
Save zzdjk6/ed5fe0bacb84167514c2816dbb33a31e to your computer and use it in GitHub Desktop.
// 1. Define the constants
const FETCH_DATA_REQUEST: string = 'FETCH_DATA/REQUEST';
const FETCH_DATA_SUCCESS: string = 'FETCH_DATA/SUCCESS';
const FETCH_DATA_FAILURE: string = 'FETCH_DATA/FAILURE';
// 2. Define action creators
const fetchDataRequest: () => Action<void> = createAction(FETCH_DATA_REQUEST);
const fetchDataSuccess: (payload: DataType) => Action<DataType> = createAction(FETCH_DATA_SUCCESS);
const fetchDataFailure: (payload: Error) => Action<Error> = createAction(FETCH_DATA_FAILURE);
// 3. Create a thunk
const fetchData = () => async (dispatch: Dispatch, getState: () => RootState) => {
dispatch(fetchDataRequest());
try {
const data = await api.fetchData();
dispatch(fetchDataSuccess(data));
} catch (e) {
dispatch(fetchDataFailure(e));
}
}
// 4. Handle actions in reducers
if (action.type === FETCH_DATA_REQUEST) {
return {
...state,
isFetching: true,
error: null
};
}
if (action.type === FETCH_DATA_SUCCESS) {
return {
...state,
isFetching: false,
data: action.payload,
error: null
};
}
if (action.type === FETCH_DATA_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