store.tsx 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { createContext, useReducer, ReactChildren } from 'react'
  2. type Action =
  3. | { type: 'beHappy' }
  4. | { type: 'addReason', reason: string }
  5. type State = {
  6. isHappy: boolean
  7. reasons: string[]
  8. }
  9. type Context = {
  10. state: State,
  11. dispatch: React.Dispatch<Action>
  12. }
  13. function reducer(state: State, action: Action): State {
  14. switch (action.type) {
  15. case 'beHappy':
  16. return {
  17. ...state,
  18. isHappy: true
  19. }
  20. case 'addReason':
  21. return {
  22. ...state,
  23. reasons: [...state.reasons, action.reason]
  24. }
  25. default:
  26. return state
  27. }
  28. }
  29. const initialState: State = {
  30. isHappy: false,
  31. reasons: []
  32. }
  33. const initialContext: Context = {
  34. state: initialState,
  35. dispatch: () => { }
  36. }
  37. const Store = createContext(initialContext)
  38. interface ProviderProps {
  39. children: ReactChildren
  40. }
  41. const StoreProvider = (props: ProviderProps) => {
  42. const [state, dispatch] = useReducer(reducer, initialState)
  43. return (
  44. <Store.Provider value={{ state, dispatch }}>
  45. {props.children}
  46. </Store.Provider >
  47. )
  48. }
  49. export { StoreProvider, Store }