Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const CHANGE_TITLE = 'REPLACE_TITLE'
- interface ReplaceTitleActionType {
- type: typeof CHANGE_TITLE
- title: string
- }
- type actionTypes = ReplaceTitleActionType
- interface IColsState {
- title: string
- }
- function reducer(state: IColsState, action: actionTypes): IColsState {
- switch (action.type) {
- case CHANGE_TITLE:
- return {
- ...state,
- title: action.title,
- }
- default:
- return {
- ...state
- }
- }
- }
- const initialState = {
- title: 'No title',
- }
- interface IColsContextState {
- state: IColsState
- dispatch: (action: actionTypes) => void
- }
- const ColsContext = React.createContext({
- state: initialState,
- dispatch: (action: actionTypes) => {}
- } as IColsContextState)
- function Test() {
- const { state, dispatch } = useContext(ColsContext)
- return (
- <div>
- <h1>{state.title}</h1>
- <button type="button" onClick={() => dispatch({ type: CHANGE_TITLE, title: 'Colin is awesome'+Math.random() })}>PRESS ME</button>
- </div>
- )
- }
- function Root() {
- const [state, dispatch] = useReducer(reducer, initialState)
- return (
- <ColsContext.Provider value={{ state, dispatch }}>
- <Test/>
- </ColsContext.Provider>
- )
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement