Created
June 22, 2020 19:06
-
-
Save gcmatheusj/106c125f20a83ad3f29ce75f27bee6a3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { createContext, useCallback, useContext, useReducer } from 'react' | |
import PropType from 'prop-types' | |
import Snackbar from '../components/Snackbar' | |
export const SnackbarContext = createContext() | |
const initialState = { | |
open: false, | |
severity: '', | |
message: '' | |
} | |
function reducer (state, action) { | |
switch (action.type) { | |
case 'open': | |
return { | |
open: true, | |
severity: action.severity, | |
message: action.message | |
} | |
case 'close': | |
return { | |
open: false, | |
severity: '', | |
message: '' | |
} | |
default: | |
throw new Error() | |
} | |
} | |
export const SnackbarProvider = ({ children }) => { | |
const [state, dispatch] = useReducer(reducer, initialState) | |
const handleOpen = useCallback( | |
({ severity, message }) => dispatch({ type: 'open', severity, message }), | |
[] | |
) | |
const handleClose = useCallback(() => dispatch({ type: 'close' }), []) | |
return ( | |
<SnackbarContext.Provider value={{ handleOpen }}> | |
<Snackbar | |
open={state.open} | |
message={state.message} | |
handleClose={handleClose} | |
/> | |
{children} | |
</SnackbarContext.Provider> | |
) | |
} | |
SnackbarProvider.propTypes = { | |
children: PropType.node.isRequired | |
} | |
export function useSnackbar () { | |
const context = useContext(SnackbarContext) | |
if (!context) { | |
throw new Error('useSnackbar must be used within a SnackbarProvider') | |
} | |
return context | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment