Created
April 20, 2024 19:51
-
-
Save abiriadev/59904587e3a5964a519fd53f8d5e1706 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 { | |
PropsWithChildren, | |
createContext, | |
useState, | |
} from 'react' | |
export const FormFactory = <T,>(init: T) => { | |
const Context = createContext<{ | |
value: T | |
setValue: <K extends keyof T>( | |
key: K, | |
value: T[K], | |
) => void | |
}>({ value: init, setValue: () => {} }) | |
const Form = ({ children }: PropsWithChildren) => { | |
const [state, setState] = useState(init) | |
return ( | |
<Context.Provider | |
value={{ | |
value: init, | |
setValue: (key, value) => | |
setState({ | |
...state, | |
[key]: value, | |
}), | |
}} | |
> | |
{children} | |
</Context.Provider> | |
) | |
} | |
return [Form, Context] as const | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment