Skip to content

Instantly share code, notes, and snippets.

@solomon-gumball
Last active August 3, 2020 22:19
Show Gist options
  • Save solomon-gumball/fe2030030ec0de1e550407c000477b0d to your computer and use it in GitHub Desktop.
Save solomon-gumball/fe2030030ec0de1e550407c000477b0d to your computer and use it in GitHub Desktop.
/**
* SomeUtilFile.tsx
*
* Generic wrapper for creating store reducer and connecting actions
*/
export function useAsyncReducer<T>(initial: T, reducer: Reducer<T, ReducerAction<T>>, actions: AsyncActions<T>): [T, ConnectedActions<T>] {
let [state, dispatch] = useReducer<T>(reducer, initial)
let connectedActions = useMemo(() => connectActionsToDispatch(actions, dispatch), [dispatch, actions])
let stateAndConnectedActions = useMemo(() => [state, connectedActions], [state, connectedActions])
return stateAndConnectedActions
}
/**
* 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, actions } from 'PatientListStore'
// ...
let patientListStore = useAsyncReducer<PatientListData>(initial, patientListReducer, actions)
return (
<PatientListContext.Provider value={patientListStore} />
)
/**
* SomeConsumerComponent.tsx
*
* Use the hook in a component
*/
import { actions, usePatientListStore } from 'PatientListStore'
// ...
let [state, { fetchPatients }] = usePatientListStore() // actions are already connected
fetchPatients()
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment