-
Notifications
You must be signed in to change notification settings - Fork 12
/
useMutation.jsx
56 lines (49 loc) · 1.39 KB
/
useMutation.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { useState, useCallback } from 'react'
import PropTypes from 'prop-types'
import useClient from './useClient'
/**
* This hook manages the state during the saving of a document
*
* @returns {import("../types").UseMutationReturnValue}
*/
const useMutation = ({ onSuccess = undefined, onError = undefined } = {}) => {
const client = useClient()
/** @type {import("../types").useState<import("../types").QueryFetchStatus>} */
const [mutationStatus, setMutationStatus] = useState('pending')
const [error, setError] = useState()
const [data, setData] = useState()
const mutate = useCallback(
async doc => {
setError(undefined)
setMutationStatus('loading')
try {
const resp = await client.save(doc)
setData(resp.data)
if (typeof onSuccess === 'function') {
await onSuccess(resp.data)
}
setMutationStatus('loaded')
} catch (e) {
setMutationStatus('failed')
setError(e)
if (typeof onError === 'function') {
await onError(e)
}
}
},
[client, onError, onSuccess]
)
return {
mutate,
mutationStatus,
error,
data
}
}
useMutation.propTypes = {
/** This function is triggered when the save is successful */
onSuccess: PropTypes.func,
/** This function is triggered when the save has failed */
onError: PropTypes.func
}
export { useMutation }