Categories
React

Getting Started with Making HTTP Requests with React Query

Spread the love

The React Query library lets us make HTTP requests easily in our React apps.

In this article, we’ll look at how to make HTTP requests with React Query.

Installation

We can install the library by running:

npm i react-query

or:

yarn add react-query

We also install the Axios HTTP client library to let us make requests easier.

To do this, we run:

npm i axios

Getting Started

We can then make a query with the API by writing:

index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { QueryClient, QueryClientProvider } from "react-query";
import App from "./App";

const queryClient = new QueryClient();

const rootElement = document.getElementById("root");
ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <StrictMode>
      <App />
    </StrictMode>
  </QueryClientProvider>,
  rootElement
);

App.js

import axios from "axios";
import React from "react";
import { useQuery } from "react-query";

export default function App() {
  const { isLoading, error, data } = useQuery("yesNo", () =>
    axios("https://yesno.wtf/api")
  );

  if (isLoading) return "Loading...";

  if (error) return "An error has occurred: " + error.message;

  return <div>{JSON.stringify(data)}</div>;
}

We wrap our App component around the QueryClientProvider component to let us use its hooks to make requests.

Then in App , we use the useQuery hook to make a GET request.

The first argument is a string identifier for our query.

The 2nd argument has a function to let us make the request.

The isLoading state indicates the request is loading when it’s truthy.

error state indicates that an error occurred when it’s truthy.

data has the response data.

Making POST Requests

To make POST requests, we can use the useMutation hook.

To do this, we write:

import axios from "axios";
import React from "react";
import { useMutation, useQueryClient } from "react-query";

export default function App() {
  const queryClient = useQueryClient();
  const mutation = useMutation(
    (data) => axios.post("https://jsonplaceholder.typicode.com/posts", data),
    {
      onSuccess: () => {
        queryClient.invalidateQueries("todos");
      }
    }
  );

  return (
    <div>
      <button
        onClick={() => {
          mutation.mutate({
            title: "foo",
            body: "bar",
            userId: 1
          });
        }}
      >
        Add Todo
      </button>
    </div>
  );
}

We keep index.js the same as in the previous example.

We call the useQueryClient hook to get the query client.

useMutation lets us make the request by passing in a callback that returns a promise by calling axios.post with the URL and request body we want.

The 2nd argument has an object that has the onSuccess callback that runs when the request succeeds.

We call queryClient.invalidaQueries with the identifier of the requests to clear resources.

Conclusion

We can make HTTP requests easily with the React Query library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *