Skip to content

Instantly share code, notes, and snippets.

@terrierscript
Created February 7, 2019 04:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terrierscript/9680aabb749b17b9162af5e6df0b9566 to your computer and use it in GitHub Desktop.
Save terrierscript/9680aabb749b17b9162af5e6df0b9566 to your computer and use it in GitHub Desktop.
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