From b770f4b74629bee0febc3e42335b62ca2d681211 Mon Sep 17 00:00:00 2001 From: Belen Curcio Date: Wed, 30 Sep 2020 13:38:39 -0300 Subject: [PATCH] Adding context --- components/core/Layout/Layout.tsx | 11 ++++++-- components/ui/context.tsx | 46 +++++++++++++++++++++++++++++++ pages/_app.tsx | 6 +++- 3 files changed, 59 insertions(+), 4 deletions(-) create mode 100644 components/ui/context.tsx diff --git a/components/core/Layout/Layout.tsx b/components/core/Layout/Layout.tsx index 22113ad4f..0ea64d4bf 100644 --- a/components/core/Layout/Layout.tsx +++ b/components/core/Layout/Layout.tsx @@ -4,6 +4,8 @@ import s from "./Layout.module.css"; import { Navbar, Featurebar } from "@components/core"; import { Container, Sidebar } from "@components/ui"; import { CartSidebarView } from "@components/cart"; +import { useUI } from "@components/ui/context"; + interface Props { className?: string; children?: any; @@ -11,6 +13,7 @@ interface Props { const Layout: FunctionComponent = ({ className, children }) => { const rootClassName = cn(s.root, className); + // const { displaySidebar } = useUI(); return ( = ({ className, children }) => { />
{children}
- {/* - - */} + {/* {displaySidebar && ( + + + + )} */}
); }; diff --git a/components/ui/context.tsx b/components/ui/context.tsx new file mode 100644 index 000000000..0ac416e4d --- /dev/null +++ b/components/ui/context.tsx @@ -0,0 +1,46 @@ +import React, { Context, FunctionComponent } from "react"; + +export interface ContextType { + displaySidebar: boolean; +} + +const initialState = { + displaySidebar: false, +}; + +function uiReducer(state, action) { + switch (action.type) { + case "OPEN_SIDEBAR": { + return { + ...state, + displaySidebar: true, + }; + } + case "CLOSE_SIDEBAR": { + return { + ...state, + displaySidebar: true, + }; + } + } +} + +export const UIContext = React.createContext(initialState); +UIContext.displayName = "UIContext"; + +export const UIProvider: FunctionComponent = (props) => { + const [state, dispatch] = React.useReducer(uiReducer, initialState); + const value = { + ...state, + dispatch, + }; + return ; +}; + +export const useUI = () => { + const context = React.useContext(UIContext); + if (context === undefined) { + throw new Error(`useUI must be used within a UIProvider`); + } + return context; +}; diff --git a/pages/_app.tsx b/pages/_app.tsx index 68a70e9de..bca14e53a 100644 --- a/pages/_app.tsx +++ b/pages/_app.tsx @@ -1,9 +1,13 @@ import "@assets/global.css"; +import React from "react"; +import { UIProvider } from "@components/ui/context"; export default function MyApp({ Component, pageProps }) { return ( <> - + + + ); }