4
0
forked from crowetic/commerce
commerce/components/ui/context.tsx

57 lines
1.2 KiB
TypeScript
Raw Normal View History

2020-10-01 09:39:31 -03:00
import React, { FunctionComponent } from "react";
2020-09-30 13:38:39 -03:00
2020-09-30 15:56:32 -03:00
export interface UIState {
displaySidebar: boolean;
2020-10-01 09:39:31 -03:00
openSidebar: () => {};
closeSidebar: () => {};
2020-09-30 15:56:32 -03:00
}
2020-09-30 13:38:39 -03:00
2020-10-01 09:39:31 -03:00
const initialState = {
displaySidebar: false,
openSidebar: null,
closeSidebar: null,
};
export const UIContext = React.createContext(initialState);
2020-09-30 13:38:39 -03:00
UIContext.displayName = "UIContext";
export const UIProvider: FunctionComponent = (props) => {
const [state, dispatch] = React.useReducer(uiReducer, initialState);
2020-10-01 09:26:22 -03:00
const openSidebar = () => dispatch("OPEN_SIDEBAR");
const closeSidebar = () => dispatch("CLOSE_SIDEBAR");
2020-09-30 13:38:39 -03:00
const value = {
...state,
2020-10-01 09:26:22 -03:00
openSidebar,
closeSidebar,
2020-09-30 13:38:39 -03:00
};
2020-10-01 09:26:22 -03:00
2020-09-30 13:38:39 -03:00
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;
};
2020-10-01 09:26:22 -03:00
function uiReducer(state, action) {
switch (action) {
case "OPEN_SIDEBAR": {
return {
...state,
displaySidebar: true,
};
}
case "CLOSE_SIDEBAR": {
return {
...state,
displaySidebar: false,
};
}
}
}