Skip to content

Instantly share code, notes, and snippets.

@multivoltage
Created April 12, 2020 10:38
Show Gist options
  • Save multivoltage/0520994ab25271af433c1dcbb7582176 to your computer and use it in GitHub Desktop.
Save multivoltage/0520994ab25271af433c1dcbb7582176 to your computer and use it in GitHub Desktop.
Simple usage for context api with value and set value written in TS
export interface I_AttachmentsContext {
urls: string[];
setUrls: (values: string[]) => void;
}
const AttachmentsContext = React.createContext<I_AttachmentsContext>({
urls: [],
setUrls: (values: string[]) => {
//
}
});
const CompA = () => {
const { setUrls } = React.useContext(AttachmentsContext);
React.useEffect(() => {
/// did mount is only an example
setUrls(["google.com"])
},[])
return <div>updater</div>
};
const CompB = () => {
const { urls } = React.useContext(AttachmentsContext);
return <div>{JSON.stringify(urls)}</div>;
};
const Wrapper = () => {
const { urls: initialUrls } = React.useContext(AttachmentsContext);
const [urls, setUrls] = React.useState<string[]>(initialUrls);
return <AttachmentsProvider value={{ urls, setUrls }}>
<CompA />
<CompB />
</AttachmentsProvider>
}
@multivoltage
Copy link
Author

I spent 1 hour to handle all types and full case for view/update values (like redux does). These lines of code do view/update cases

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment