Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.