index.tsx
38 lines
| 1 | import {createContext, ReactNode, useContext, useReducer} from 'react'; |
| 2 | import type {Gateway} from '@givewp/forms/types'; |
| 3 | import reducer from '@givewp/forms/app/store/reducer'; |
| 4 | import {ObjectSchema} from 'joi'; |
| 5 | |
| 6 | const StoreContext = createContext(null); |
| 7 | StoreContext.displayName = 'DonationFormState'; |
| 8 | |
| 9 | const StoreContextDispatch = createContext(null); |
| 10 | StoreContextDispatch.displayName = 'DonationFormStateDispatch'; |
| 11 | |
| 12 | type PropTypes = { |
| 13 | initialState: { |
| 14 | gateways: Gateway[]; |
| 15 | defaultValues: object; |
| 16 | validationSchema: ObjectSchema; |
| 17 | }; |
| 18 | children: ReactNode; |
| 19 | }; |
| 20 | |
| 21 | /** |
| 22 | * @since 3.0.0 |
| 23 | */ |
| 24 | const DonationFormStateProvider = ({initialState, children}: PropTypes) => { |
| 25 | const [state, dispatch] = useReducer(reducer, initialState); |
| 26 | |
| 27 | return ( |
| 28 | <StoreContext.Provider value={state}> |
| 29 | <StoreContextDispatch.Provider value={dispatch}>{children}</StoreContextDispatch.Provider> |
| 30 | </StoreContext.Provider> |
| 31 | ); |
| 32 | }; |
| 33 | |
| 34 | const useDonationFormState = () => useContext<PropTypes['initialState']>(StoreContext); |
| 35 | const useDonationFormStateDispatch = () => useContext(StoreContextDispatch); |
| 36 | |
| 37 | export {DonationFormStateProvider, useDonationFormState, useDonationFormStateDispatch}; |
| 38 |