diff --git a/src/index.jsx b/src/index.jsx index abf04eb..126a756 100644 --- a/src/index.jsx +++ b/src/index.jsx @@ -6,6 +6,7 @@ import * as serviceWorker from "./serviceWorker"; import { Auth0Provider } from "./utils/auth0-spa"; import history from "./utils/history"; import { FirebaseContext } from "./services/Firebase"; +import { AppProvider } from "./store/meal"; const onRedirectCallBack = (appState) => { history.push( @@ -24,7 +25,9 @@ ReactDOM.render( > {/* todo fix Firebase app*/} - + + + , document.getElementById("root") diff --git a/src/store/meal/actions.ts b/src/store/meal/actions.ts new file mode 100644 index 0000000..8a4da09 --- /dev/null +++ b/src/store/meal/actions.ts @@ -0,0 +1,2 @@ +export type Action = { type: "fetchMeal" | "fetchRandomMeal" | "toggleFav" }; +export type Dispatch = (action: Action) => void; diff --git a/src/store/meal/index.tsx b/src/store/meal/index.tsx new file mode 100644 index 0000000..7fabedb --- /dev/null +++ b/src/store/meal/index.tsx @@ -0,0 +1,30 @@ +//https://kentcdodds.com/blog/how-to-use-react-context-effectively + +import { createContext, FC, useContext, useReducer } from "react"; +import { MealApi } from "../../types/meal"; +import { Dispatch } from "./actions"; +import { appReducer } from "./reducer"; + +const AppContext = createContext< + | { + state: AppState; + dispatch: Dispatch; + } + | undefined +>(undefined); + +export type AppState = { meals: MealApi[] }; + +export const useMeal = () => { + const context = useContext(AppContext); + if (!context) { + throw new Error("useMeal must be used within a AppProvider"); + } + return context; +}; + +export const AppProvider: FC = ({ children }) => { + const [state, dispatch] = useReducer(appReducer, { meals: [] as MealApi[] }); + const value = { state, dispatch }; + return {children}; +}; diff --git a/src/store/meal/reducer.ts b/src/store/meal/reducer.ts new file mode 100644 index 0000000..554ad91 --- /dev/null +++ b/src/store/meal/reducer.ts @@ -0,0 +1,16 @@ +import { Action } from "./actions"; +import { AppState } from "./index"; + +export const appReducer = (state: AppState, action: Action) => { + switch (action.type) { + case "fetchMeal": + return { meals: state.meals }; + case "fetchRandomMeal": + return { meals: state.meals }; + case "toggleFav": + return { meals: state.meals }; + default: { + throw new Error(`Unhandled action type: ${action.type}`); + } + } +};