Created
June 22, 2021 21:28
-
-
Save destinio/1904562e101e2fda40366d8bd68dd1bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { createContext, useContext, useReducer } from 'react' | |
interface StateInterface { | |
data: string[] | |
} | |
interface Actions { | |
type: string | |
payload: any | |
} | |
type AppContextType = { | |
state: StateInterface | |
dispatch: React.Dispatch<Actions> | |
} | |
const AppContext = createContext<AppContextType>(null!) | |
export function useAppContext(): AppContextType { | |
return useContext(AppContext) | |
} | |
const initState = { | |
data: [] | |
} | |
function appReducer(state: StateInterface, action:Actions) { | |
switch (action.type) { | |
case 'SET_DATA': | |
return {...state, data: [...state.data, action.payload]} | |
default: | |
return state | |
} | |
} | |
type Props = { | |
children: React.ReactNode | |
} | |
export default function AppContextProvider({children}: Props): React.ReactElement { | |
const [state, dispatch] = useReducer(appReducer, initState) | |
return <AppContext.Provider value={{ state, dispatch }}>{children}</AppContext.Provider> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment