index.tsx
49 lines
| 1 | import {createContext, ReactElement, ReactNode, useContext} from 'react'; |
| 2 | import {useImmerReducer} from 'use-immer'; |
| 3 | import reducer from './reducer'; |
| 4 | |
| 5 | const StoreContext = createContext(null); |
| 6 | StoreContext.displayName = 'DonationSummaryProvider'; |
| 7 | |
| 8 | const StoreContextDispatch = createContext(null); |
| 9 | StoreContextDispatch.displayName = 'DonationSummaryDispatch'; |
| 10 | |
| 11 | export type DonationTotals = {[key: string]: number}; |
| 12 | export type DonationSummaryItems = {[key: string]: DonationSummaryLineItem}; |
| 13 | |
| 14 | /** |
| 15 | * @since 3.0.0 |
| 16 | */ |
| 17 | export type DonationSummaryLineItem = { |
| 18 | id: string; |
| 19 | label: string; |
| 20 | value: string | ReactElement; |
| 21 | description?: string | ReactElement; |
| 22 | }; |
| 23 | |
| 24 | type PropTypes = { |
| 25 | initialState?: { |
| 26 | items: DonationSummaryItems; |
| 27 | totals: DonationTotals; |
| 28 | }; |
| 29 | children: ReactNode; |
| 30 | }; |
| 31 | |
| 32 | /** |
| 33 | * @since 3.0.0 |
| 34 | */ |
| 35 | const DonationSummaryProvider = ({initialState = {items: {}, totals: {}}, children}: PropTypes) => { |
| 36 | const [state, dispatch] = useImmerReducer(reducer, initialState); |
| 37 | |
| 38 | return ( |
| 39 | <StoreContext.Provider value={state}> |
| 40 | <StoreContextDispatch.Provider value={dispatch}>{children}</StoreContextDispatch.Provider> |
| 41 | </StoreContext.Provider> |
| 42 | ); |
| 43 | }; |
| 44 | |
| 45 | const useDonationSummaryContext = () => useContext<PropTypes['initialState']>(StoreContext); |
| 46 | const useDonationSummaryDispatch = () => useContext(StoreContextDispatch); |
| 47 | |
| 48 | export {DonationSummaryProvider, useDonationSummaryContext, useDonationSummaryDispatch}; |
| 49 |