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

48 lines
1.0 KiB
TypeScript
Raw Normal View History

2020-09-30 13:38:39 -03:00
import React, { Context, FunctionComponent } from "react";
const initialState = {
displaySidebar: false,
2020-09-30 15:56:32 -03:00
dispatch: null,
2020-09-30 13:38:39 -03:00
};
2020-09-30 15:56:32 -03:00
export interface UIState {
displaySidebar: boolean;
dispatch: (string) => void;
}
2020-09-30 13:38:39 -03:00
function uiReducer(state, action) {
2020-09-30 15:56:32 -03:00
switch (action) {
2020-09-30 13:38:39 -03:00
case "OPEN_SIDEBAR": {
return {
...state,
displaySidebar: true,
};
}
case "CLOSE_SIDEBAR": {
return {
...state,
2020-09-30 15:56:32 -03:00
displaySidebar: false,
2020-09-30 13:38:39 -03:00
};
}
}
}
2020-09-30 15:56:32 -03:00
export const UIContext = React.createContext<UIState>(initialState);
2020-09-30 13:38:39 -03:00
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;
};