use react query to post json data to an api in typescript

To use react-query to make a POST request with JSON data to an API, follow these steps:

  1. Install react-query using npm or yarn:
npm install react-query
24 chars
2 lines


yarn add react-query
21 chars
2 lines
  1. Create a function to make the POST request:
import { useMutation } from "react-query";

interface PostData {
  name: string;
  age: number;

async function postData(data: PostData) {
  const response = await fetch("", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    body: JSON.stringify(data),

  if (!response.ok) {
    throw new Error("Network response was not ok");

  return response.json();
431 chars
23 lines
  1. Use the useMutation hook to call the postData function and pass the JSON data:
function App() {
  const [name, setName] = useState("");
  const [age, setAge] = useState(0);

  const [postMutation, { status }] = useMutation(postData);

  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {

    postMutation({ name, age });

  return (
    <form onSubmit={handleSubmit}>
        <input type="text" value={name} onChange={(e) => setName(} />
      <br />
        <input type="number" value={age} onChange={(e) => setAge(parseInt(} />
      <br />
      <button type="submit" disabled={status === "loading"}>
        {status === "loading" ? "Submitting..." : "Submit"}
781 chars
31 lines

This code will create a form with two inputs for name and age, and a button to submit the data. When the button is clicked, postMutation will be called with the JSON data, and React Query will handle the network request and update the status accordingly.

Note: This code assumes that react-query and react are already imported and set up in the project.

gistlibby LogSnag