|
| 1 | +import { useCallback, useEffect, useRef, useState } from 'react' |
| 2 | + |
| 3 | +import { PostgrestError } from '../types' |
| 4 | +import { useClient } from './use-client' |
| 5 | +import { initialState } from './state' |
| 6 | + |
| 7 | +export type UseInsertState<Data = any> = { |
| 8 | + count?: number | null |
| 9 | + data?: Data | Data[] | null |
| 10 | + error?: PostgrestError | null |
| 11 | + fetching: boolean |
| 12 | +} |
| 13 | + |
| 14 | +export type UseInsertResponse<Data = any> = [ |
| 15 | + UseInsertState<Data>, |
| 16 | + ( |
| 17 | + values: Partial<Data> | Partial<Data>[], |
| 18 | + options?: UseInsertOptions, |
| 19 | + ) => Promise<Pick<UseInsertState<Data>, 'count' | 'data' | 'error'>>, |
| 20 | +] |
| 21 | + |
| 22 | +export type UseInsertOptions = { |
| 23 | + returning?: 'minimal' | 'representation' |
| 24 | + count?: null | 'exact' | 'planned' | 'estimated' |
| 25 | +} |
| 26 | + |
| 27 | +export type UseInsertConfig = { |
| 28 | + options?: UseInsertOptions |
| 29 | +} |
| 30 | + |
| 31 | +export function useInsert<Data = any>( |
| 32 | + table: string, |
| 33 | + config: UseInsertConfig = { options: {} }, |
| 34 | +): UseInsertResponse<Data> { |
| 35 | + const client = useClient() |
| 36 | + const isMounted = useRef(false) |
| 37 | + const [state, setState] = useState<UseInsertState>(initialState) |
| 38 | + |
| 39 | + /* eslint-disable react-hooks/exhaustive-deps */ |
| 40 | + const execute = useCallback( |
| 41 | + async ( |
| 42 | + values: Partial<Data> | Partial<Data>[], |
| 43 | + options?: UseInsertOptions, |
| 44 | + ) => { |
| 45 | + setState({ ...initialState, fetching: true }) |
| 46 | + const { count, data, error } = await client |
| 47 | + .from<Data>(table) |
| 48 | + .insert(values, options ?? config.options) |
| 49 | + if (isMounted.current) setState({ data, error, fetching: false }) |
| 50 | + return { count, data, error } |
| 51 | + }, |
| 52 | + [client], |
| 53 | + ) |
| 54 | + /* eslint-enable react-hooks/exhaustive-deps */ |
| 55 | + |
| 56 | + useEffect(() => { |
| 57 | + isMounted.current = true |
| 58 | + return () => { |
| 59 | + isMounted.current = false |
| 60 | + } |
| 61 | + }, []) |
| 62 | + |
| 63 | + return [state, execute] |
| 64 | +} |
0 commit comments