Sitemap
Saeed Badghaish

Saeed Badghaish

I am an accomplished coder and programmer, and I enjoy using my skills to contribute to the exciting technological advances that happen every day

Make requests with React Query

1 min readOct 2, 2022

You can make requests with the useQuery hook, which takes an identifier for your query (in this case, since we are fetching user data, we will call it ‘user’), plus a function that is used to fetch that data.

import { useQuery } from "react-query";

export default function App() {
const { isLoading, isError, data } = useQuery("user", () =>
fetch("https://randomuser.me/api").then((res) => res.json())
);

if (isLoading) return "Loading...";
if (isError) return "Error!";

const user = data.results[0];
return user.email;
}

Get Saeed Badghaish’s stories in your inbox

Join Medium for free to get updates from this writer.

As you can see, React Query takes care of managing these various states that can take place when we fetch our data. We no longer need to manage these states ourselves, we can just destructure them from what is returned from useQuery.

Where does the state management part of useQuery come into play?

Now that we have fetched the user data and have it stored in our internal cache, all we need to do to be able to use it across any other component is to call useQuery() with the 'user' key that we associated with it:

import { useQuery } from "react-query";

export default function OtherComponent() {
const { data } = useQuery('user');

console.log(data);
}

--

--

Saeed Badghaish
Saeed Badghaish

Written by Saeed Badghaish

0 followers

I am an accomplished coder and programmer, and I enjoy using my skills to contribute to the exciting technological advances that happen every day