|
| 1 | +import { useCallback, useEffect, useRef, useState } from 'react' |
| 2 | + |
| 3 | +import { Count, Filter, PostgrestError, Returning } from '../../types' |
| 4 | +import { useClient } from '../use-client' |
| 5 | +import { initialState } from './state' |
| 6 | + |
| 7 | +export type UseUpsertState<Data = any> = { |
| 8 | + count?: number | null |
| 9 | + data?: Data | Data[] | null |
| 10 | + error?: PostgrestError | null |
| 11 | + fetching: boolean |
| 12 | +} |
| 13 | + |
| 14 | +export type UseUpsertResponse<Data = any> = [ |
| 15 | + UseUpsertState<Data>, |
| 16 | + ( |
| 17 | + values: Partial<Data> | Partial<Data>[], |
| 18 | + options?: UseUpsertOptions, |
| 19 | + filter?: Filter<Data>, |
| 20 | + ) => Promise<Pick<UseUpsertState<Data>, 'count' | 'data' | 'error'>>, |
| 21 | +] |
| 22 | + |
| 23 | +export type UseUpsertOptions = { |
| 24 | + count?: null | Count |
| 25 | + onConflict?: string |
| 26 | + returning?: Returning |
| 27 | +} |
| 28 | + |
| 29 | +export type UseUpsertConfig<Data = any> = { |
| 30 | + filter?: Filter<Data> |
| 31 | + options?: UseUpsertOptions |
| 32 | +} |
| 33 | + |
| 34 | +export function useUpsert<Data = any>( |
| 35 | + table: string, |
| 36 | + config: UseUpsertConfig<Data> = { options: {} }, |
| 37 | +): UseUpsertResponse<Data> { |
| 38 | + const client = useClient() |
| 39 | + const isMounted = useRef(false) |
| 40 | + const [state, setState] = useState<UseUpsertState>(initialState) |
| 41 | + |
| 42 | + /* eslint-disable react-hooks/exhaustive-deps */ |
| 43 | + const execute = useCallback( |
| 44 | + async ( |
| 45 | + values: Partial<Data> | Partial<Data>[], |
| 46 | + options?: UseUpsertOptions, |
| 47 | + filter?: Filter<Data>, |
| 48 | + ) => { |
| 49 | + const refine = filter ?? config.filter |
| 50 | + setState({ ...initialState, fetching: true }) |
| 51 | + const source = client |
| 52 | + .from<Data>(table) |
| 53 | + .upsert(values, options ?? config.options) |
| 54 | + |
| 55 | + const { count, data, error } = await (refine |
| 56 | + ? refine(source) |
| 57 | + : source) |
| 58 | + |
| 59 | + const res = { count, data, error } |
| 60 | + if (isMounted.current) setState({ ...res, fetching: false }) |
| 61 | + return res |
| 62 | + }, |
| 63 | + [client], |
| 64 | + ) |
| 65 | + /* eslint-enable react-hooks/exhaustive-deps */ |
| 66 | + |
| 67 | + useEffect(() => { |
| 68 | + isMounted.current = true |
| 69 | + return () => { |
| 70 | + isMounted.current = false |
| 71 | + } |
| 72 | + }, []) |
| 73 | + |
| 74 | + return [state, execute] |
| 75 | +} |
0 commit comments