Backbencher.dev

Get Data From API Using Query in React Query Version 2

Last updated on 25 Jul, 2021

Query in React Query can be used to resolve promises and fetch data from an API. Here, we are fetching data from Github user search API.

First, import useQuery hook from react-query.

Now, in our functional component use the useQuery hook.

const queryUsers = useQuery("gitUsers", () =>
  fetch("https://api.github.com/search/users?q=joby").then((res) => res.json())
);

Each time the status of request changes, we could see re-rendering of the component. We can print the value of queryUsers in console. The final value of queryUsers will be having the Github users.

React Query Data

This way of using useQuery will not work in React Query version 3. There we need to use QueryClientProvider along with useQuery.

--- ○ ---
Joby Joseph
Web Architect