You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.3 KiB
TypeScript
55 lines
1.3 KiB
TypeScript
2 years ago
|
import { useEffect, useState } from 'preact/hooks'
|
||
|
|
||
2 years ago
|
import { createContext } from 'preact'
|
||
2 years ago
|
import { server } from './api.jsx'
|
||
2 years ago
|
|
||
|
export const MetadataContext = createContext({})
|
||
|
|
||
|
export const useCurrentUser = onLoaded => {
|
||
2 years ago
|
const [user, setUser] = useState(null)
|
||
|
|
||
2 years ago
|
const logout = async () => {
|
||
|
await server.post('/api/logout')
|
||
2 years ago
|
setUser(null)
|
||
|
}
|
||
2 years ago
|
|
||
|
useEffect(async () => {
|
||
2 years ago
|
const user = await server.get('/api/current-user')
|
||
2 years ago
|
setUser(user)
|
||
|
onLoaded?.(user)
|
||
2 years ago
|
}, [])
|
||
|
|
||
2 years ago
|
return [user, logout]
|
||
2 years ago
|
}
|
||
2 years ago
|
|
||
|
export const useReadResource = (url, initialValue) => {
|
||
|
const [value, setValue] = useState(initialValue)
|
||
|
|
||
|
function refresh() {
|
||
|
const controller = new AbortController()
|
||
2 years ago
|
const realUrl = typeof url === 'function' ? url() : url
|
||
|
fetch(realUrl, { signal: controller.signal })
|
||
2 years ago
|
.then(res => {
|
||
|
if (res.ok) {
|
||
|
return res.json()
|
||
|
} else {
|
||
|
return initialValue
|
||
|
}
|
||
|
})
|
||
|
.then(newValue => {
|
||
|
setValue(newValue)
|
||
|
})
|
||
|
|
||
|
return controller
|
||
|
}
|
||
|
|
||
|
useEffect(() => {
|
||
|
const controller = refresh()
|
||
|
return () => {
|
||
|
controller.abort()
|
||
|
}
|
||
|
}, [])
|
||
|
|
||
|
return [value, refresh]
|
||
|
}
|