Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. const CHANGE_TITLE = 'REPLACE_TITLE'
  2.  
  3. interface ReplaceTitleActionType {
  4. type: typeof CHANGE_TITLE
  5. title: string
  6. }
  7.  
  8. type actionTypes = ReplaceTitleActionType
  9.  
  10. interface IColsState {
  11. title: string
  12. }
  13.  
  14. function reducer(state: IColsState, action: actionTypes): IColsState {
  15. switch (action.type) {
  16. case CHANGE_TITLE:
  17. return {
  18. ...state,
  19. title: action.title,
  20. }
  21.  
  22. default:
  23. return {
  24. ...state
  25. }
  26. }
  27. }
  28.  
  29. const initialState = {
  30. title: 'No title',
  31. }
  32.  
  33. interface IColsContextState {
  34. state: IColsState
  35. dispatch: (action: actionTypes) => void
  36. }
  37.  
  38. const ColsContext = React.createContext({
  39. state: initialState,
  40. dispatch: (action: actionTypes) => {}
  41. } as IColsContextState)
  42.  
  43. function Test() {
  44. const { state, dispatch } = useContext(ColsContext)
  45.  
  46. return (
  47. <div>
  48. <h1>{state.title}</h1>
  49. <button type="button" onClick={() => dispatch({ type: CHANGE_TITLE, title: 'Colin is awesome'+Math.random() })}>PRESS ME</button>
  50. </div>
  51. )
  52. }
  53.  
  54. function Root() {
  55. const [state, dispatch] = useReducer(reducer, initialState)
  56.  
  57. return (
  58. <ColsContext.Provider value={{ state, dispatch }}>
  59. <Test/>
  60. </ColsContext.Provider>
  61. )
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement