magic: added a way for running async functions in the top level jsx code

This commit is contained in:
2023-01-11 21:38:37 +01:00
parent 71280fba5c
commit fab8398a7a
8 changed files with 91 additions and 44 deletions
+12 -1
View File
@@ -1,7 +1,9 @@
import { StateUpdater, useEffect, useState } from 'preact/hooks'
import { StateUpdater, useContext, useEffect, useState } from 'preact/hooks'
import { createContext } from 'preact'
import { prependBaseUrl } from '../shared/utils'
import { DatabaseConnection } from '../shared/database'
import { ServerAsyncCallback } from '../shared/ssr'
type Metadata = {
title?: string
@@ -13,6 +15,8 @@ export const MetadataContext = createContext<Metadata>({})
export const ServerContext = createContext<boolean>(false)
export const ClientContext = createContext<boolean>(false)
export const DatabaseContext = createContext<DatabaseConnection | null>(null)
type RefreshFunction = () => AbortController
type HeuristicStateUpdater<S> = StateUpdater<S>
@@ -73,3 +77,10 @@ export const useListResource = <T,>(
return [list, refreshList, setItemHeuristic, setListHeuristic]
}
export const ServerAsyncCallbacksContext = createContext<ServerAsyncCallback[]>([])
export const useServerAsyncCallback = (fn: () => Promise<void>) => {
const registeredAsyncCallbacks = useContext(ServerAsyncCallbacksContext)
registeredAsyncCallbacks.push(fn)
}