Skip to content

Commit 5a5ad74

Browse files
committed
fix(useMutation): ensure all side-effects are always called
Fixes TanStack#249 Now all we need is the new test from TanStack#641
1 parent 2de8528 commit 5a5ad74

File tree

1 file changed

+14
-41
lines changed

1 file changed

+14
-41
lines changed

src/react/useMutation.js

Lines changed: 14 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -80,64 +80,37 @@ export function useMutation(mutationFn, config = {}) {
8080

8181
const isLatest = () => latestMutationRef.current === mutationId
8282

83-
dispatch({ type: actionLoading })
84-
8583
let snapshotValue
8684

8785
try {
86+
dispatch({ type: actionLoading })
8887
snapshotValue = await config.onMutate(variables)
8988

90-
let data
91-
92-
if (isLatest()) {
93-
data = await getMutationFn()(variables)
94-
}
89+
let data = await getMutationFn()(variables)
9590

9691
if (isLatest()) {
9792
dispatch({ type: actionResolve, data })
9893
}
9994

100-
if (isLatest()) {
101-
await config.onSuccess(data, variables)
102-
}
103-
104-
if (isLatest()) {
105-
await onSuccess(data, variables)
106-
}
107-
108-
if (isLatest()) {
109-
await config.onSettled(data, null, variables)
110-
}
111-
112-
if (isLatest()) {
113-
await onSettled(data, null, variables)
114-
}
95+
await config.onSuccess(data, variables)
96+
await onSuccess(data, variables)
97+
await config.onSettled(data, null, variables)
98+
await onSettled(data, null, variables)
11599

116100
return data
117101
} catch (error) {
118-
if (isLatest()) {
119-
Console.error(error)
120-
await config.onError(error, variables, snapshotValue)
121-
}
122-
123-
if (isLatest()) {
124-
await onError(error, variables, snapshotValue)
125-
}
126-
127-
if (isLatest()) {
128-
await config.onSettled(undefined, error, variables, snapshotValue)
129-
}
130-
131-
if (isLatest()) {
132-
await onSettled(undefined, error, variables, snapshotValue)
133-
}
102+
Console.error(error)
103+
await config.onError(error, variables, snapshotValue)
104+
await onError(error, variables, snapshotValue)
105+
await config.onSettled(undefined, error, variables, snapshotValue)
106+
await onSettled(undefined, error, variables, snapshotValue)
134107

135108
if (isLatest()) {
136109
dispatch({ type: actionReject, error })
110+
}
137111

138-
if (throwOnError ?? config.throwOnError) {
139-
throw error
140-
}
112+
if (throwOnError ?? config.throwOnError) {
113+
throw error
141114
}
142115
}
143116
},

0 commit comments

Comments
 (0)