React Query

React Query is a library, Used to fetch data asynchronously

Prerequisites –

  • Create react app
  • React Js basics and Hooks
  • Axios
  • Async/Await functions

Getting started

Add React query to your react app npm Install react-query run this comment to add

import { QueryClient, QueryClientProvider } from "react-query";

function App({ userDetail }: emailtype) {
  const client = new QueryClient();
  return (
    <>
    	    <QueryClientProvider client={client}>
            <Home />
          </QueryClientProvider>   
    </>
  );
}

Import QueryClient and QueryClientProvider from react-query wrap with your App component with QueryClientProvider give QueryClient() to the QueryClientProvider

Api Call –

Import useQuery. useQuery needs two arguments 1st  is api name, 2nd argument is a axios call.

import { useQuery } from "react-query";
  const { data, isLoading, isError, error, isFetching } = useQuery("sampleapi", () =>
    axios.get("https://sampleapi.com/getusers")
  );
  • data if the query is in success state, the data will be available in data property
  • isLoading the query has no data and is currently fetching
  • isError if query has an error
  • error if the query has an error, it will show in error property            
  • isFetching the query has data and is currently fetching

Sample implementation

function Example() {
  const { isLoading, error, data } = useQuery("repoData", () =>
    fetch("https://sampleapi.com/getusers").then(
      (res) => res.json()
    )
  );

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

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

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.description}</p>
      <strong>{data.email}</strong>
      <strong>{data.username}</strong>
    </div>
  );
}

Dependent queries

Dependent queires depend on previous query to achieve that you have to use `enabled` to tell the query when to run

const { data: user } = useQuery(
  ["user", email],
  axios.get("https://sampleapi.com/getusers")
);

const userId = user?.id;

// Then get the user's projects
const { isIdle, data: projects } = useQuery(
  ["projects", userId],
  axios.get("https://sampleapi.com/getprojectsusers"),
  {
    // The query will not execute until the userId exists
    enabled: !!userId,
  }
);

Related Blogs

Empower your organization with Microsoft 365, a versatile platform designed for...
Empower your organization with Microsoft 365, a versatile platform designed for...