Last active
June 3, 2022 00:24
-
-
Save sidneyroberto/c57ced50de2617a266cb58e7488af7ce 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 { createContext, ReactNode, useEffect, useState } from 'react' | |
type UserType = { | |
token: string | |
userName: string | |
setToken: (newState: string) => void | |
setUserName: (newState: string) => void | |
} | |
const initialValue: UserType = { | |
token: localStorage.getItem('token') || '', | |
setToken: () => {}, | |
userName: localStorage.getItem('userName') || '', | |
setUserName: () => {}, | |
} | |
export const UserContext = createContext(initialValue) | |
type Props = { | |
children: ReactNode | |
} | |
export const UserContextProvider = ({ children }: Props) => { | |
const [token, setToken] = useState(initialValue.token) | |
const [userName, setUserName] = useState(initialValue.userName) | |
useEffect(() => { | |
localStorage.setItem('token', token) | |
localStorage.setItem('userName', userName) | |
}, [token, userName]) | |
return ( | |
<UserContext.Provider | |
value={{ | |
token, | |
setToken, | |
userName, | |
setUserName, | |
}} | |
> | |
{children} | |
</UserContext.Provider> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment