Skip to content

Instantly share code, notes, and snippets.

@emartini
Created June 23, 2019 15:36
Show Gist options
  • Save emartini/6edad1cfdc72960ff519df55919e8110 to your computer and use it in GitHub Desktop.
Save emartini/6edad1cfdc72960ff519df55919e8110 to your computer and use it in GitHub Desktop.
How to use createContext with an useState as value
import React, { createContext, useContext, useState } from "react";
interface PageView {
user?: {
sessionId?: string;
};
}
type ContextType = [PageView, React.Dispatch<React.SetStateAction<PageView>>];
export const PageViewContext = createContext<ContextType>([{}, () => () => {}]);
export const PageViewProvider: React.FunctionComponent<{}> = ({ children }) => {
const [pageView, setPageView] = useState({});
return (
<PageViewContext.Provider value={[pageView, setPageView]}>
{children}
</PageViewContext.Provider>
);
};
export const usePageViewContext = () => useContext(PageViewContext);
const Consumer = () => {
const [pageView] = useContext(PageViewContext);
return (
<code>
<pre>{JSON.stringify(pageView, null, 2)}</pre>
</code>
);
};
// https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript#comment13539914_8084248
const rs = () =>
Math.random()
.toString(36)
.substring(2, 6);
const SessionIdUpdater = () => {
const [pageView, setPageView] = usePageViewContext();
const callback = () => {
const { user = {} as PageView["user"] } = { ...pageView };
user!.sessionId = `${rs()}-${rs()}-${rs()}`;
setPageView({
...pageView,
...{ user }
});
};
return <button onClick={callback}>Randomize Session ID</button>;
};
const App: React.FunctionComponent<{}> = () => {
return (
<PageViewProvider>
<Consumer />
<SessionIdUpdater />
</PageViewProvider>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment