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:
index.ts
npm install react-query
24 chars
2 lines

or

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

interface PostData {
  name: string;
  age: number;
}

async function postData(data: PostData) {
  const response = await fetch("https://example.com/api", {
    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:
index.ts
function App() {
  const [name, setName] = useState("");
  const [age, setAge] = useState(0);

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

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

    postMutation({ name, age });
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
      </label>
      <br />
      <label>
        Age:
        <input type="number" value={age} onChange={(e) => setAge(parseInt(e.target.value))} />
      </label>
      <br />
      <button type="submit" disabled={status === "loading"}>
        {status === "loading" ? "Submitting..." : "Submit"}
      </button>
    </form>
  );
}
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