Created
July 23, 2019 10:05
-
-
Save zzdjk6/030624fd2bfd4572531ebbfeda702676 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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