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.

Revisions

  1. dbritto-dev created this gist Oct 24, 2024.
    53 changes: 53 additions & 0 deletions auth-context.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    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>
    }