12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- import { createContext, useReducer, ReactChildren } from 'react'
- type Action =
- | { type: 'beHappy' }
- | { type: 'addReason', reason: string }
- type State = {
- isHappy: boolean
- reasons: string[]
- }
- type Context = {
- state: State,
- dispatch: React.Dispatch<Action>
- }
- function reducer(state: State, action: Action): State {
- switch (action.type) {
- case 'beHappy':
- return {
- ...state,
- isHappy: true
- }
- case 'addReason':
- return {
- ...state,
- reasons: [...state.reasons, action.reason]
- }
- default:
- return state
- }
- }
- const initialState: State = {
- isHappy: false,
- reasons: []
- }
- const initialContext: Context = {
- state: initialState,
- dispatch: () => { }
- }
- const Store = createContext(initialContext)
- interface ProviderProps {
- children: ReactChildren
- }
- const StoreProvider = (props: ProviderProps) => {
- const [state, dispatch] = useReducer(reducer, initialState)
- return (
- <Store.Provider value={{ state, dispatch }}>
- {props.children}
- </Store.Provider >
- )
- }
- export { StoreProvider, Store }
|