Skip to content

Commit 3148c72

Browse files
committed
feature: add Playground cancelQueries method example
1 parent e4c603b commit 3148c72

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

playground/src/App.tsx

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -133,31 +133,52 @@ function PetCard({ pet }: { pet: components['schemas']['Pet'] }) {
133133
function PetUpdateForm({ petId }: { petId: number }) {
134134
const { setPetIdToEditToEdit } = usePetToEdit();
135135

136-
const petQueryKey = qraft.pet.getPetById.getQueryKey({
136+
const petParameters: typeof qraft.pet.getPetById.types.parameters = {
137137
path: { petId },
138-
});
138+
};
139139

140140
const {
141141
data: pet,
142142
isPending: isPetQueryPending,
143143
error: petQueryError,
144-
} = qraft.pet.getPetById.useQuery(petQueryKey, { enabled: !!petId });
144+
} = qraft.pet.getPetById.useQuery(petParameters, { enabled: !!petId });
145145

146146
const queryClient = useQueryClient();
147147

148148
const { isPending, mutate } = qraft.pet.updatePet.useMutation(undefined, {
149-
onMutate(variables) {
149+
async onMutate(variables) {
150+
await qraft.pet.getPetById.cancelQueries(
151+
{ parameters: petParameters },
152+
queryClient
153+
);
154+
155+
const prevPet = qraft.pet.getPetById.getQueryData(
156+
petParameters,
157+
queryClient
158+
);
159+
150160
qraft.pet.getPetById.setQueryData(
151-
petQueryKey,
161+
petParameters,
152162
(oldData) => ({
153163
...oldData,
154164
...variables.body,
155165
}),
156166
queryClient
157167
);
168+
169+
return { prevPet };
170+
},
171+
async onError(_error, _variables, context) {
172+
if (context?.prevPet) {
173+
qraft.pet.getPetById.setQueryData(
174+
petParameters,
175+
context.prevPet,
176+
queryClient
177+
);
178+
}
158179
},
159180
async onSuccess(updatedPet) {
160-
qraft.pet.getPetById.setQueryData(petQueryKey, updatedPet, queryClient);
181+
qraft.pet.getPetById.setQueryData(petParameters, updatedPet, queryClient);
161182
await qraft.pet.findPetsByStatus.invalidateQueries(queryClient);
162183
setPetIdToEditToEdit(undefined);
163184
},

0 commit comments

Comments
 (0)