1
1
import { useCallback , useEffect , useRef , useState } from 'react'
2
2
3
- import { Count , PostgrestError , Returning } from '../types'
3
+ import { Count , Filter , PostgrestError , Returning } from '../types'
4
4
import { useClient } from './use-client'
5
5
import { initialState } from './state'
6
6
@@ -15,6 +15,7 @@ export type UseUpdateResponse<Data = any> = [
15
15
UseUpdateState < Data > ,
16
16
(
17
17
values : Partial < Data > ,
18
+ filter ?: Filter < Data > ,
18
19
options ?: UseUpdateOptions ,
19
20
) => Promise < Pick < UseUpdateState < Data > , 'count' | 'data' | 'error' > > ,
20
21
]
@@ -24,27 +25,39 @@ export type UseUpdateOptions = {
24
25
count ?: null | Count
25
26
}
26
27
27
- export type UseUpdateConfig = {
28
+ export type UseUpdateConfig < Data = any > = {
29
+ filter ?: Filter < Data >
28
30
options ?: UseUpdateOptions
29
31
}
30
32
31
33
export function useUpdate < Data = any > (
32
34
table : string ,
33
- config : UseUpdateConfig = { options : { } } ,
35
+ config : UseUpdateConfig < Data > = { options : { } } ,
34
36
) : UseUpdateResponse < Data > {
35
37
const client = useClient ( )
36
38
const isMounted = useRef ( false )
37
39
const [ state , setState ] = useState < UseUpdateState > ( initialState )
38
40
39
41
/* eslint-disable react-hooks/exhaustive-deps */
40
42
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
+
42
52
setState ( { ...initialState , fetching : true } )
43
- const { count , data , error } = await client
53
+ const source = client
44
54
. from < Data > ( table )
45
55
. 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
48
61
} ,
49
62
[ client ] ,
50
63
)
0 commit comments