11import { useCallback , useEffect , useRef , useState } from 'react'
22
3- import { Count , PostgrestError , Returning } from '../types'
3+ import { Count , Filter , PostgrestError , Returning } from '../types'
44import { useClient } from './use-client'
55import { initialState } from './state'
66
@@ -15,6 +15,7 @@ export type UseUpdateResponse<Data = any> = [
1515 UseUpdateState < Data > ,
1616 (
1717 values : Partial < Data > ,
18+ filter ?: Filter < Data > ,
1819 options ?: UseUpdateOptions ,
1920 ) => Promise < Pick < UseUpdateState < Data > , 'count' | 'data' | 'error' > > ,
2021]
@@ -24,27 +25,39 @@ export type UseUpdateOptions = {
2425 count ?: null | Count
2526}
2627
27- export type UseUpdateConfig = {
28+ export type UseUpdateConfig < Data = any > = {
29+ filter ?: Filter < Data >
2830 options ?: UseUpdateOptions
2931}
3032
3133export function useUpdate < Data = any > (
3234 table : string ,
33- config : UseUpdateConfig = { options : { } } ,
35+ config : UseUpdateConfig < Data > = { options : { } } ,
3436) : UseUpdateResponse < Data > {
3537 const client = useClient ( )
3638 const isMounted = useRef ( false )
3739 const [ state , setState ] = useState < UseUpdateState > ( initialState )
3840
3941 /* eslint-disable react-hooks/exhaustive-deps */
4042 const execute = useCallback (
41- async ( values : Partial < Data > , options ?: UseUpdateOptions ) => {
43+ async (
44+ values : Partial < Data > ,
45+ filter ?: Filter < Data > ,
46+ options ?: UseUpdateOptions ,
47+ ) => {
48+ const refine = filter ?? config . filter
49+ if ( refine === undefined )
50+ throw Error ( 'update() should always be combined with `filter`' )
51+
4252 setState ( { ...initialState , fetching : true } )
43- const { count , data , error } = await client
53+ const source = client
4454 . from < Data > ( table )
4555 . update ( values , options ?? config . options )
46- if ( isMounted . current ) setState ( { data, error, fetching : false } )
47- return { count, data, error }
56+ const { count, data, error } = await refine ( source )
57+
58+ const res = { count, data, error }
59+ if ( isMounted . current ) setState ( { ...res , fetching : false } )
60+ return res
4861 } ,
4962 [ client ] ,
5063 )
0 commit comments