Skip to content

Commit 7ca0888

Browse files
committed
fix: merge conflict
2 parents 5ce6c87 + 2ca3fda commit 7ca0888

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed

src/hooks/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export * from './use-client'
22
export * from './use-filter'
3+
export * from './use-insert'
34
export * from './use-select'
45
export * from './use-update'

src/hooks/use-insert.ts

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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+
}

test/use-insert.test.tsx

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { renderHook } from '@testing-library/react-hooks'
2+
3+
import { useInsert } from '../src'
4+
5+
describe('useSelect', () => {
6+
it('should throw when not inside Provider', () => {
7+
const { result } = renderHook(() => useInsert('todos'))
8+
expect(result.error).toEqual(
9+
Error('No client has been specified using Provider.'),
10+
)
11+
})
12+
})

0 commit comments

Comments
 (0)