Last active
January 6, 2022 15:27
-
-
Save cchudant/b6348df8efcb956dc3400cae7577dc94 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { createContext, useContext } from 'react' | |
interface User { | |
name: string | |
} | |
interface UserContext { | |
value?: User | |
setCurrentUser: (value: User) => void | |
} | |
const CurrentUserContext = createContext<UserContext | null>(null) | |
export function ProvideUser(props: { children: any }) { | |
const [currentUser, setCurrentUser] = useState<User | undefined>(undefined) | |
const context: UserContext = { | |
value: currentUser, | |
setCurrentUser: (value) => setCurrentUser(value) | |
} | |
return ( | |
<CurrentUserContext.Provider value={context}> | |
{props.children} | |
</CurrentUserContext.Provider> | |
) | |
} | |
function ConsumerPage() { | |
const { value: currentUser, setCurrentUser } = useContext(CurrentUserContext)! | |
return ( | |
<div onClick={() => setCurrentUser({ name: 'autre' })}> | |
{currentUser ? currentUser.name : 'not connected'} | |
</div> | |
) | |
} | |
function App() { | |
return ( | |
<ProvideUser> | |
<ConsumerPage /> | |
</ProvideUser> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment