Skip to content

Instantly share code, notes, and snippets.

@dbritto-dev
Created October 24, 2024 21:43
Show Gist options
  • Save dbritto-dev/1ed6a98b9dde81a2e9d340f0f751e359 to your computer and use it in GitHub Desktop.
Save dbritto-dev/1ed6a98b9dde81a2e9d340f0f751e359 to your computer and use it in GitHub Desktop.
AuthContext
import { useState, createContext, useMemo, useCallback, useContext } from 'react'
const AuthContext = createContext(undefined)
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(undefined)
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState(null)
const login = useCallback(async () => {
try {
setIsLoading(true)
const nextUser = await fetch(`http://api.com/login`)
setUser(nextUser)
} catch (nextError) {
setError(nextError.message)
} finally {
setIsLoading(false)
}
}, [])
const logout = useCallback(async () => {
await fetch(`http://api.com/logout`)
}, [])
const auth = useMemo(
() => ({
user,
isLoading,
error,
login,
logout,
}),
[user, isLoading, error, login, logout]
)
return <AuthContext.Provider value={auth}>{children}</AuthContext.Provider>
}
export const useAuth = () => {
const auth = useContext(AuthContext)
if (auth === undefined) throw Error(`useAuth must be within AuthProvider`)
return auth
}
const Component = () => {
const { isLoading, error, user } = useAuth()
if (isLoading) return <div>Loading...</div>
if (error) return <div>Error: {error}!</div>
if (!user) return <div>Unauthenticated</div>
return <div>Authenticated</div>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment