Skip to content

Instantly share code, notes, and snippets.

@solomon-gumball
Last active August 3, 2020 22:15
Show Gist options
  • Save solomon-gumball/80a150b775ea975c7dca7db79222ace5 to your computer and use it in GitHub Desktop.
Save solomon-gumball/80a150b775ea975c7dca7db79222ace5 to your computer and use it in GitHub Desktop.
/**
* 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