Skip to content

Commit b559194

Browse files
fix(hooks/single): pass 'hasBeenUpdated' to local callback
1 parent be6bcf3 commit b559194

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

lib/hooks/single.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { FormEvent, useCallback, useEffect, useState } from 'react';
1+
import { FormEvent, useCallback, useEffect, useRef, useState } from 'react';
22
import { AxiosError } from 'axios';
33
import { dequal } from 'dequal/lite';
44
import to from 'await-to-js';
@@ -58,6 +58,8 @@ export default function useSingle<T>(
5858
const [checked, setChecked] = useState<boolean>(false);
5959
const [validations, setValidations] = useState<Validations>({});
6060

61+
const lastReceivedResponse = useRef<T>(initialData);
62+
6163
const onSubmit = useCallback(
6264
async (evt?: FormEvent) => {
6365
// Validate submission data.
@@ -80,7 +82,9 @@ export default function useSingle<T>(
8082
} else {
8183
// Otherwise, mutate local data with the server's response.
8284
if (res && !dequal(res, data)) {
85+
lastReceivedResponse.current = res;
8386
setData(res);
87+
// TODO: This is unnecessary if `options.sync` is true.
8488
if (updateLocal) await updateLocal(res, true);
8589
} else if (updateLocal) {
8690
// Signal that local data is now in sync with server data.
@@ -103,7 +107,9 @@ export default function useSingle<T>(
103107
useEffect(() => {
104108
if (!options?.sync || !updateLocal) return;
105109
const throttle = options.throttle || 500;
106-
const timeoutId = setTimeout(() => updateLocal(data, false), throttle);
110+
const timeoutId = setTimeout(() => {
111+
void updateLocal(data, dequal(lastReceivedResponse.current, data));
112+
}, throttle);
107113
return () => clearTimeout(timeoutId);
108114
}, [data, updateLocal, options]);
109115

0 commit comments

Comments
 (0)