DEV Community

Shin-Young Jung
Shin-Young Jung

Posted on

Manual Fetch with Tanstack Query

TanStack Query (FKA React Query) is often described as the missing data-fetching library for web applications, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your web applications a breeze. - TanStack Query Overview

As a developer, TanStak Query is very efficient tool that handle all our needs when we fetch the data through APIs.

Very often we want to fetch the query manually not from useEffect or automatic fetching when entering the page.

To achieve this manual query, we can use QueryClient.

As all of you know, we already define the QueryClient to use the TanStack Query in our service.

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

function App() {
  return <QueryClientProvider client={queryClient}>
    <Main />

Enter fullscreen mode Exit fullscreen mode

If you want to use the queryClient that you define above, you can simply use the hook called useQueryClient in your code.

import { useQueryClient } from '@tanstack/react-query';

export default function Main() {
  const queryClient = useQueryClient();
Enter fullscreen mode Exit fullscreen mode

And then, you can use the function called fetchQuery. fetchQuery works exactly like useQuery, so we can add queryKey, queryFn, and other options that useQuery uses. (See the available options from the official documentation.

Here is an example.

const handleClick = async () => {
  try {
    // data will be the response of the fetch
    const data = await queryClient.fetchQuery({
        queryKey: ['fetch-data'],
        queryFn: functionForFetch(),
  } catch (e){
    // handling error...

<button onClick={handleClick}>Fetch</button>

Enter fullscreen mode Exit fullscreen mode

Top comments (0)