Skip to content
Myr

index.ts

This file

Path

src/jsx/dom/hooks/index.ts

91 lines · 2.4 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–91why, one step back
1/**
2 * Provide hooks used only in jsx/dom3 */45import { PERMALINK } from '../../constants'6import type { Context } from '../../context'7import { useContext } from '../../context'8import { useCallback, useState } from '../../hooks'9import { createContext } from '../context'1011type FormStatus =12 | {13 pending: false14 data: null15 method: null16 action: null17 }18 | {19 pending: true20 data: FormData21 method: 'get' | 'post'22 action: string | ((formData: FormData) => void | Promise<void>)23 }24export const FormContext: Context<FormStatus> = createContext<FormStatus>({25 pending: false,26 data: null,27 method: null,28 action: null,29})3031const actions: Set<Promise<unknown>> = new Set()32export const registerAction = (action: Promise<unknown>) => {33 actions.add(action)34 action.finally(() => actions.delete(action))35}3637/**38 * This hook returns the current form status39 * @returns FormStatus40 */41export const useFormStatus = (): FormStatus => {42 return useContext(FormContext)43}4445/**46 * This hook returns the current state and a function to update the state optimistically47 * The current state is updated optimistically and then reverted to the original state when all actions are resolved48 * @param state49 * @param updateState50 * @returns [T, (action: N) => void]51 */52export const useOptimistic = <T, N>(53 state: T,54 updateState: (currentState: T, action: N) => T55): [T, (action: N) => void] => {56 const [optimisticState, setOptimisticState] = useState(state)57 if (actions.size > 0) {58 Promise.all(actions).finally(() => {59 setOptimisticState(state)60 })61 } else {62 setOptimisticState(state)63 }6465 const cb = useCallback((newData: N) => {66 setOptimisticState((currentState) => updateState(currentState, newData))67 }, [])6869 return [optimisticState, cb]70}7172/**73 * This hook returns the current state and a function to update the state by form action74 * @param fn75 * @param initialState76 * @param permalink77 * @returns [T, (data: FormData) => void]78 */79export const useActionState = <T>(80 fn: Function,81 initialState: T,82 permalink?: string83): [T, Function] => {84 const [state, setState] = useState(initialState)85 const actionState = async (data: FormData) => {86 setState(await fn(state, data))87 }88 // eslint-disable-next-line @typescript-eslint/no-explicit-any89 ;(actionState as any)[PERMALINK] = permalink90 return [state, actionState]91}