Debian Codegraph @

examples/react-spa/frontend/src/auth/AuthContext.js

raw
1 import { useEffect, createContext, useState } from 'react'
2 import { getAuth, getConfig } from '../lib/allauth'
3
4 export const AuthContext = createContext(null)
5
6 function Loading () {
7 return <div>Starting...</div>
8 }
9
10 function LoadingError () {
11 return <div>Loading error!</div>
12 }
13
14 export function AuthContextProvider (props) {
15 const [auth, setAuth] = useState(undefined)
16 const [config, setConfig] = useState(undefined)
17
18 useEffect(() => {
19 function onAuthChanged (e) {
20 setAuth(auth => {
21 if (typeof auth === 'undefined') {
22 console.log('Authentication status loaded')
23 } else {
24 console.log('Authentication status updated')
25 }
26 return e.detail
27 }
28 )
29 }
30
31 document.addEventListener('allauth.auth.change', onAuthChanged)
32 getAuth().then(data => setAuth(data)).catch((e) => {
33 console.error(e)
34 setAuth(false)
35 })
36 getConfig().then(data => setConfig(data)).catch((e) => {
37 console.error(e)
38 })
39 return () => {
40 document.removeEventListener('allauth.auth.change', onAuthChanged)
41 }
42 }, [])
43 const loading = (typeof auth === 'undefined') || config?.status !== 200
44 return (
45 <AuthContext.Provider value={{ auth, config }}>
46 {loading
47 ? <Loading />
48 : (auth === false
49 ? <LoadingError />
50 : props.children)}
51 </AuthContext.Provider>
52 )
53 }