Skip to content

Instantly share code, notes, and snippets.

@Plsr
Created November 19, 2022 20:57
Show Gist options
  • Save Plsr/1b7be7d0d5320c8e3f2412408f0583ef to your computer and use it in GitHub Desktop.
Save Plsr/1b7be7d0d5320c8e3f2412408f0583ef to your computer and use it in GitHub Desktop.
react-query useMutation multiple in sequence
import { useMutation } from "@tanstack/react-query";
const mockApiUrl = "https://untitled-l5q2pajt3yo0.runkit.sh/post";
const mutateFn = async () => {
const res = await fetch(mockApiUrl, {
method: "POST",
mode: "cors",
});
if (!res.ok) {
throw new Error("Request failed");
}
const data = await res.json();
return data;
};
export default function Home() {
const { mutateAsync } = useMutation(mutateFn);
const handleFetchClick = async () => {
const req1 = mutateAsync();
const req2 = mutateAsync();
const req3 = mutateAsync();
const req4 = mutateAsync();
const results = await Promise.allSettled([req1, req2, req3, req4]);
console.log(results);
console.log(results.find(result => result.status === 'fulfilled'))
};
return (
<div>
<p>Here be magic</p>
<button onClick={handleFetchClick}>Fetch</button>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment