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

57 lines
1.1 KiB
TypeScript
Raw Normal View History

2020-10-01 21:30:52 -05:00
import React, { FC } from 'react'
2020-09-30 13:38:39 -03:00
2020-09-30 15:56:32 -03:00
export interface UIState {
2020-10-01 20:40:40 -05:00
displaySidebar: boolean
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,
2020-10-01 20:40:40 -05:00
}
2020-10-01 09:39:31 -03:00
2020-10-01 20:40:40 -05:00
export const UIContext = React.createContext(initialState)
UIContext.displayName = 'UIContext'
2020-09-30 13:38:39 -03:00
2020-10-01 21:30:52 -05:00
export const UIProvider: FC = (props) => {
2020-10-01 20:40:40 -05:00
const [state, dispatch] = React.useReducer(uiReducer, initialState)
2020-10-01 09:26:22 -03:00
2020-10-01 20:40:40 -05:00
const openSidebar = () => dispatch('OPEN_SIDEBAR')
const closeSidebar = () => dispatch('CLOSE_SIDEBAR')
2020-10-01 09:26:22 -03:00
2020-09-30 13:38:39 -03:00
const value = {
...state,
2020-10-01 09:26:22 -03:00
openSidebar,
closeSidebar,
2020-10-01 20:40:40 -05:00
}
2020-10-01 09:26:22 -03:00
2020-10-01 20:40:40 -05:00
return <UIContext.Provider value={value} {...props} />
}
2020-09-30 13:38:39 -03:00
export const useUI = () => {
2020-10-01 20:40:40 -05:00
const context = React.useContext(UIContext)
2020-09-30 13:38:39 -03:00
if (context === undefined) {
2020-10-01 20:40:40 -05:00
throw new Error(`useUI must be used within a UIProvider`)
2020-09-30 13:38:39 -03:00
}
2020-10-01 20:40:40 -05:00
return context
}
2020-10-01 09:26:22 -03:00
function uiReducer(state, action) {
switch (action) {
2020-10-01 20:40:40 -05:00
case 'OPEN_SIDEBAR': {
2020-10-01 09:26:22 -03:00
return {
...state,
displaySidebar: true,
2020-10-01 20:40:40 -05:00
}
2020-10-01 09:26:22 -03:00
}
2020-10-01 20:40:40 -05:00
case 'CLOSE_SIDEBAR': {
2020-10-01 09:26:22 -03:00
return {
...state,
displaySidebar: false,
2020-10-01 20:40:40 -05:00
}
2020-10-01 09:26:22 -03:00
}
}
}