Created
February 27, 2024 15:29
-
-
Save brunoh3art/b2269c70d57a0557e278872471cebc9c to your computer and use it in GitHub Desktop.
create Safe Context
This file contains hidden or 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, useContext } from "react"; | |
| export function createSafeContext<ContextValue>(errorMessage: string) { | |
| const Context = createContext<ContextValue | null>(null); | |
| const useSafeContext = () => { | |
| const ctx = useContext(Context); | |
| if (ctx === null) { | |
| throw new Error(errorMessage); | |
| } | |
| return ctx; | |
| }; | |
| const Provider = ({ children, value }: { value: ContextValue; children: React.ReactNode }) => ( | |
| <Context.Provider value={value}>{children}</Context.Provider> | |
| ); | |
| return [Provider, useSafeContext] as const; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment