Created
February 7, 2023 10:43
-
-
Save AlexMachin1997/5dc20f410c6995617236ad7aa34ba54b to your computer and use it in GitHub Desktop.
Attempting to have a strongly typed React Context
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 * as React from "react"; | |
import PropTypes from "prop-types"; | |
export const AuthRequiredModalContext = React.createContext<boolean>(false); | |
interface AuthRequiredContextInterface { | |
isAuthRequiredModalOpen: boolean; | |
setIsAuthRequiredModalOpen: React.Dispatch<React.SetStateAction<boolean>>; | |
} | |
export const AuthRequiredModalProvider = ({ | |
children, | |
}: { | |
children: React.ReactNode; | |
}) => { | |
const [isAuthRequiredModalOpen, setIsAuthRequiredModalOpen] = | |
React.useState<boolean>(false); | |
const value = React.useMemo<AuthRequiredContextInterface>( | |
() => ({ | |
isAuthRequiredModalOpen, | |
setIsAuthRequiredModalOpen, | |
}), | |
[isAuthRequiredModalOpen, setIsAuthRequiredModalOpen] | |
); | |
return ( | |
<AuthRequiredModalContext.Provider value={value}> | |
{children} | |
</AuthRequiredModalContext.Provider> | |
); | |
}; | |
export const useAuthRequiredModalState = () => { | |
const context = React.useContext(AuthRequiredModalContext); | |
if (!context) | |
throw Error( | |
"useAuthRequiredModalState requires a AuthRequiredModalProvider" | |
); | |
return context; | |
}; | |
AuthRequiredModalProvider.propTypes = { | |
children: PropTypes.oneOfType([ | |
PropTypes.node, | |
PropTypes.object, | |
PropTypes.func, | |
]).isRequired, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment