Categories
React

Making HTTP Requests with React Query — Loading State and Refetching

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.

Global Background Fetching Loading State

We can get the loading of all requests where any requests are loading.

To do this, we can use the useIsFetching hook.

For instance, we can write:

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

  if (isFetching) {
    return "loading";
  }

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

to call the useIsFetching hook to check whether any requests in our app is loading.

Window Focus Refetching

By default, React Query will automatically request fresh data in the background when we focus on the window.

To disable this, we can set refrechOnWindowFocus to false when we create the QueryClient instance.

To do this for all requests, we 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({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false
    }
  }
});

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, useIsFetching } from "react-query";
export default function App() {
  const isFetching = useIsFetching();
  const { data } = useQuery(["todo", 1], ({ queryKey: [, id] }) => {
    return axios(`https://jsonplaceholder.typicode.com/posts/${id}`);
  });

  if (isFetching) {
    return "loading";
  }

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

We can also disable this option per query 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, useIsFetching } from "react-query";
export default function App() {
  const isFetching = useIsFetching();
  const { data } = useQuery(
    ["todo", 1],
    ({ queryKey: [, id] }) => {
      return axios(`https://jsonplaceholder.typicode.com/posts/${id}`);
    },
    { refetchOnWindowFocus: false }
  );

  if (isFetching) {
    return "loading";
  }

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

Disabling or Pausing Queries

We can disable a query from automatically running with the enabled property set to false .

For instance, we can write:

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

  return (
    <div>
      <button onClick={() => refetch()}>Fetch Todo</button>
      <div>{JSON.stringify(data)}</div>
    </div>
  );
}

We set enabled to false so that the request won’t be made when the component mounts.

To make the request, we can use the refetch function to make the request.

Conclusion

We can get the loading state of requests and control when requests are made with React Query.

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 *