Created
February 7, 2019 04:07
-
-
Save terrierscript/9680aabb749b17b9162af5e6df0b9566 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, Context, useContext } from "react" | |
interface SafetyContextValue extends Object { | |
isDefault: boolean | |
} | |
export const createSafetyContext = <T extends SafetyContextValue>( | |
defaultValue: T | |
) => { | |
return createContext({ | |
...defaultValue, | |
isDefault: true | |
}) | |
} | |
export const useSafetyContext = <T extends SafetyContextValue>( | |
context: Context<T> | |
) => { | |
const { isDefault, ...values } = useContext(context) | |
if (isDefault) { | |
throw new Error("This context is not provided") | |
} | |
return values | |
} | |
export const generateSafetyProvider = (Context) => { | |
return ({ value, children }) => { | |
const _value = { | |
...value, | |
isDefault: false | |
} | |
return <Context.Provider value={_value}>{children}</Context.Provider> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment