Skip to content

Commit dbab2e5

Browse files
committed
docs(examples): demonstrate abortable mutations
1 parent 08f76f2 commit dbab2e5

1 file changed

Lines changed: 27 additions & 2 deletions

File tree

examples/react-app/src/App.tsx

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import "./App.css";
2-
import { useState } from "react";
2+
import { useEffect, useRef, useState } from "react";
33

44
import {
55
UseFindPetsKeyFn,
@@ -26,7 +26,15 @@ function App() {
2626
const { data: notDefined } = useGetNotDefined<undefined>();
2727
const { mutate: mutateNotDefined } = usePostNotDefined<undefined>();
2828

29-
const { mutate: addPet, isError } = useAddPet();
29+
const { mutate: addPet, isError, isPending: isAddingPet } = useAddPet();
30+
const addPetAbortController = useRef<AbortController | null>(null);
31+
32+
useEffect(
33+
() => () => {
34+
addPetAbortController.current?.abort();
35+
},
36+
[],
37+
);
3038

3139
const [text, setText] = useState<string>("");
3240
const [errorText, setErrorText] = useState<string>();
@@ -53,9 +61,14 @@ function App() {
5361
<button
5462
type="button"
5563
onClick={() => {
64+
addPetAbortController.current?.abort();
65+
const controller = new AbortController();
66+
addPetAbortController.current = controller;
67+
5668
addPet(
5769
{
5870
body: { name: text },
71+
signal: controller.signal,
5972
},
6073
{
6174
onSuccess: () => {
@@ -68,12 +81,24 @@ function App() {
6881
console.log(error.response);
6982
setErrorText(`Error: ${error.response?.data.message}`);
7083
},
84+
onSettled: () => {
85+
if (addPetAbortController.current === controller) {
86+
addPetAbortController.current = null;
87+
}
88+
},
7189
},
7290
);
7391
}}
7492
>
7593
Create a pet
7694
</button>
95+
<button
96+
type="button"
97+
disabled={!isAddingPet}
98+
onClick={() => addPetAbortController.current?.abort()}
99+
>
100+
Cancel pet creation
101+
</button>
77102
{isError && (
78103
<p
79104
style={{

0 commit comments

Comments
 (0)