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

2 years ago
import { useEffect, useState } from 'preact/hooks'
import { createContext } from 'preact'
import { server } from './api.jsx'
export const MetadataContext = createContext({})
export const useCurrentUser = onLoaded => {
const [user, setUser] = useState(null)
const logout = async () => {
await server.post('/api/logout')
setUser(null)
}
2 years ago
useEffect(async () => {
const user = await server.get('/api/current-user')
setUser(user)
onLoaded?.(user)
2 years ago
}, [])
return [user, logout]
2 years ago
}
export const useReadResource = (url, initialValue) => {
const [value, setValue] = useState(initialValue)
function refresh() {
const controller = new AbortController()
const realUrl = typeof url === 'function' ? url() : url
fetch(realUrl, { signal: controller.signal })
.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]
}