Created
December 23, 2022 22:18
-
-
Save kevinvdburgt/e702cb290adcf1daa60482b2f7029ffc 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
export const AuthProvider: FunctionComponent<AuthProviderProps> = (props) => { | |
const { children } = props; | |
const [token, setToken] = useLocalStorage<string | null>({ | |
key: 'auth.token', | |
defaultValue: null, | |
getInitialValueInEffect: true, | |
}); | |
const [user, setUser] = useLocalStorage<UsersMeResponse | null>({ | |
key: 'auth.user', | |
defaultValue: null, | |
getInitialValueInEffect: true, | |
}); | |
useEffect(() => { | |
if (token) { | |
requestUsersMe() | |
.then((response) => setUser(response)) | |
.catch(() => { | |
setUser(null); | |
setToken(null); | |
}); | |
} | |
}, [token]); | |
const login = useCallback((t: string) => { | |
setToken(t); | |
}, []); | |
const logout = useCallback(() => { | |
setToken(null); | |
setUser(null); | |
}, []); | |
return <AuthContext.Provider value={{ user, token, login, logout }}>{children}</AuthContext.Provider>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment