4
0
forked from crowetic/commerce

Adding context

This commit is contained in:
Belen Curcio 2020-09-30 13:38:39 -03:00
parent 1de43d9074
commit b770f4b746
3 changed files with 59 additions and 4 deletions

View File

@ -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<Props> = ({ className, children }) => {
const rootClassName = cn(s.root, className);
// const { displaySidebar } = useUI();
return (
<Container className={rootClassName}>
<Featurebar
@ -19,9 +22,11 @@ const Layout: FunctionComponent<Props> = ({ className, children }) => {
/>
<Navbar />
<main className="h-screen">{children}</main>
{/* <Sidebar>
<CartSidebarView />
</Sidebar> */}
{/* {displaySidebar && (
<Sidebar>
<CartSidebarView />
</Sidebar>
)} */}
</Container>
);
};

46
components/ui/context.tsx Normal file
View File

@ -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<ContextType>(initialState);
UIContext.displayName = "UIContext";
export const UIProvider: FunctionComponent = (props) => {
const [state, dispatch] = React.useReducer(uiReducer, initialState);
const value = {
...state,
dispatch,
};
return <UIContext.Provider value={value} {...props} />;
};
export const useUI = () => {
const context = React.useContext(UIContext);
if (context === undefined) {
throw new Error(`useUI must be used within a UIProvider`);
}
return context;
};

View File

@ -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 (
<>
<Component {...pageProps} />
<UIProvider>
<Component {...pageProps} />
</UIProvider>
</>
);
}