Almost MVP

This commit is contained in:
2022-11-22 04:03:32 +01:00
parent ea3b7aeecf
commit dcaa052f30
19 changed files with 430 additions and 134 deletions
+32 -5
View File
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'preact/hooks'
import { StateUpdater, useEffect, useState } from 'preact/hooks'
import { createContext } from 'preact'
import { server } from './api'
@@ -10,6 +10,9 @@ type Metadata = {
export const MetadataContext = createContext<Metadata>({})
export const ServerContext = createContext<boolean>(false)
export const ClientContext = createContext<boolean>(false)
type CurrentUserHook = (
onLoaded?: (user: User | null) => void
) => [User | null, () => Promise<void>]
@@ -32,12 +35,17 @@ export const useCurrentUser: CurrentUserHook = onLoaded => {
return [user, logout]
}
type ReadResourceFunction = <T>(
type RefreshFunction = () => AbortController
type HeuristicStateUpdater<S> = StateUpdater<S>
type ResourceHookFunction = <T>(
url: string | (() => string),
initialValue: T
) => [T, () => AbortController]
) => [T, RefreshFunction, HeuristicStateUpdater<T>]
export const useResource: ResourceHookFunction = (url, initialValue) => {
//
export const useReadResource: ReadResourceFunction = (url, initialValue) => {
const [value, setValue] = useState(initialValue)
function refresh() {
@@ -65,5 +73,24 @@ export const useReadResource: ReadResourceFunction = (url, initialValue) => {
}
}, [])
return [value, refresh]
return [value, refresh, setValue]
}
type HeuristicListItemUpdater<S> = (index: number, value: S | ((prevValue: S) => S)) => void
export const useListResource = <T,>(
url: string | (() => string)
): [T[], RefreshFunction, HeuristicListItemUpdater<T>, HeuristicStateUpdater<T[]>] => {
const [list, refreshList, setListHeuristic] = useResource<T[]>(url, [])
const setItemHeuristic: HeuristicListItemUpdater<T> = (index, newValue) => {
setListHeuristic(list => {
const newList = [...list]
// @ts-ignore
newList[index] = typeof newValue === 'function' ? newValue(list[index]) : newValue
return newList
})
}
return [list, refreshList, setItemHeuristic, setListHeuristic]
}