Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

auth.tsx

63 lines1.3 KB

1import * as React from 'react'
2​
3import { sleep } from './utils'
4​
5export interface AuthContext {
6 isAuthenticated: boolean
7 login: (username: string) => Promise<void>
8 logout: () => Promise<void>
9 user: string | null
11​
12const AuthContext = React.createContext<AuthContext | null>(null)
13​
14const key = 'tanstack.auth.user'
15​
16function getStoredUser() {
17 return localStorage.getItem(key)
19​
20function setStoredUser(user: string | null) {
21 if (user) {
22 localStorage.setItem(key, user)
23 } else {
24 localStorage.removeItem(key)
25 }
27​
28export function AuthProvider({ children }: { children: React.ReactNode }) {
29 const [user, setUser] = React.useState<string | null>(getStoredUser())
30 const isAuthenticated = !!user
31​
32 const logout = React.useCallback(async () => {
33 await sleep(250)
34​
35 setStoredUser(null)
36 setUser(null)
37 }, [])
38​
39 const login = React.useCallback(async (username: string) => {
40 await sleep(500)
41​
42 setStoredUser(username)
43 setUser(username)
44 }, [])
45​
46 React.useEffect(() => {
47 setUser(getStoredUser())
48 }, [])
49​
50 return (
51 <AuthContext.Provider value={{ isAuthenticated, user, login, logout }}>
52 {children}
53 </AuthContext.Provider>
54 )
56​
57export function useAuth() {
58 const context = React.useContext(AuthContext)
59 if (!context) {
60 throw new Error('useAuth must be used within an AuthProvider')
61 }
62 return context