Created
April 12, 2020 10:38
-
-
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
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
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> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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