Last active
August 3, 2020 22:15
-
-
Save solomon-gumball/80a150b775ea975c7dca7db79222ace5 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* SomeUtilFile.tsx | |
* | |
* Generic wrapper for async dispatch | |
*/ | |
export function useAsyncReducer<T>(initial: T, reducer: Reducer<T, Action>): [T, AsyncDispatch<T>] { | |
let [state, dispatch] = useReducer<T>(reducer, initial) | |
let wrappedDispatch = useMemo(() => wrappedDispatch(dispatch), [dispatch]) | |
let stateWithWrappedDispatch = useMemo(() => [state, wrappedDispatch], [state, wrappedDispatch]) | |
return stateWithWrappedDispatch | |
} | |
/** | |
* PatientListStore.tsx | |
* | |
* Declare and export store actions | |
*/ | |
export const actions = { | |
fetchPatients: () => PlatformProtected.fetchPatients().then(this.setPatients), | |
setPatients: (patients) => ({ type: ActionTypes.SetPatient, payload: patients }) | |
} | |
/** | |
* ParentAppProtected.tsx | |
* | |
* Create the store in some component and add to provider | |
*/ | |
import { PatientListContext, initial, reducer } from 'PatientListStore' | |
// ... | |
let patientListStore = useAsyncReducer<PatientListData>(initial, patientListReducer) | |
return ( | |
<PatientListContext.Provider value={patientListStore} /> | |
) | |
/** | |
* SomeConsumerComponent.tsx | |
* | |
* Use the hook in a component | |
*/ | |
import { actions, usePatientListStore } from 'PatientListStore' | |
// ... | |
let [state, dispatch] = usePatientListStore() | |
dispatch(actions.fetchPatients()) | |
// ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment