Categories
React

Making HTTP Requests with React Query — Query Functions

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.

Query Functions

Query functions are functions that returns a promise and it’s passed into the 2nd argument of the useQuery hook.

For instance, we can write:

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 { data } = useQuery("yesNo", () => axios("https://yesno.wtf/api"));

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

to return the promise return by the axios function.

The returned promises’ data will be set as the value of the data property.

Handling and Throwing Errors

React Query expects that an error is thrown in the query function when an error occurred.

If it doesn’t then we’ve to throw it ourselves.

For instance, we can write:

import React from "react";
import { useQuery } from "react-query";
export default function App() {
  const { error } = useQuery("todo", async () => {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/posts/100000000000"
    );
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    return response.json();
  });

  return <div>{error && error.message}</div>;
}

If we use the Fetch API to make HTTP requests, then we’ve to check whether the response.ok property is true .

If it’s not, then we’ve to throw an error to let React Query know that an error has occurred.

This has to be done since fetch doesn’t throw an error when we get a non-200 series response.

If response.ok is true , we return the response by calling response.json() .

Query Object

We can pass in a query object instead of pass in every as separate arguments to make our GET request.

For instance, we can write:

import axios from "axios";
import React from "react";
import { useQuery } from "react-query";
export default function App() {
  const { data } = useQuery({
    queryKey: ["todo", 1],
    queryFn: ({ queryKey: [, id] }) => {
      return axios(`https://jsonplaceholder.typicode.com/posts/${id}`);
    }
  });

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

queryKey has the identifier of the request.

queryFn is the function for making the request.

Conclusion

We can pass in functions that returns a promise to make requests to the useQuery hook to make GET requests with React.

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 *