Get In Touch
Diamond Marg, Kupondole heights ,
Lalitpur-10 ,Nepal,
dev@ux-qode.com
Ph: +977 980-1039816
Work Inquiries
dev@ux-qode.com
Ph: +977 980-1039816
Back

Combining Directus with TanStack React Query for Efficient Data Fetching

Directus is an open-source data platform that turns any SQL database into a headless CMS, providing a powerful API for managing data. TanStack React Query is a data-fetching library that simplifies fetching, caching, synchronising, and updating server state in React applications. Combining Directus and React Query can create an efficient, scalable, and reactive frontend that seamlessly interacts with Directus’ API.

In this guide, we will explore how to combine Directus and TanStack React Query for effective data management and fetching in React applications.

Key Concepts in Directus & React Query Integration:

  • Directus API: Directus provides a flexible API to interact with your SQL database. It supports REST and GraphQL endpoints for fetching and manipulating data.
  • React Query: React Query helps manage remote data by providing hooks to fetch, cache, and synchronise the data with minimal boilerplate.

Benefits of Using Directus with React Query

  • Declarative Data Fetching: React Query allows you to declaratively fetch and manage data from Directus, reducing boilerplate code.
  • Automatic Caching: React Query caches responses from the Directus API, avoiding unnecessary refetches and reducing API requests.
  • Stale-While-Revalidate: It enables data to be shown instantly while refetching fresh data from Directus in the background.
  • Error Handling: React Query has built-in mechanisms for handling loading and error states.
  • Automatic Refetching: It can automatically re-fetch data when the query keys change, keeping your app’s data up-to-date.

Steps to Combine Directus with React Query

1. Setting up Directus

First, install and configure Directus on your server or use Directus Cloud. Directus provides a robust API for interacting with the data.

npm install directus

Next, initialise Directus and create a client instance for fetching data:

import { createDirectus, rest } from “@directus/sdk”;

// Set up the Directus client

const apiUrl = process.env.NEXT_PUBLIC_API_URL || ‘https://your_url’);

export const client = createDirectus(‘https://your_url’).with(rest({});

This instance will be used to interact with the Directus API.

2. Installing React Query

To set up React Query, you first need to install the necessary packages:

npm install @tanstack/react-query

React Query comes with a QueryClient that handles caching, garbage collection, and other core functionalities.

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

const queryClient = new QueryClient();

function App() {

  return (

    <QueryClientProvider client={queryClient}>

      <YourComponent />

    </QueryClientProvider>

  );

}

The QueryClientProvider wraps your application, giving access to React Query’s features.

3. Fetching Data from Directus with React Query

To fetch data from Directus, you can use the useQuery hook from React Query. This hook automatically manages the fetching state (loading, success, and error).

import { useQuery } from ‘@tanstack/react-query’;

const fetchData = async () => {

  const data = await client.request(readItems(‘your_collection_name’));

  return data;

};

//Create a Custom Hook (Not mandatory but nice to have)

export const useData = ()=>{

  const { data, isPending, isError } = useQuery({

queryFn: fetchData,

key:[“data”],

});

return {data,isError,isPending};

};

function YourComponent() {

 const { data, isError, isPending } =  useData();

if (isPending)

 return <p>Loading…</p>;

if (isError)

 return <p>Error loading data</p>;

return( 

<div>

    {data?.data.map(item => (

    <div key={item.id}>{item.title}</div>

    ))}

  </div> 

); 

}

  • Query Key: The first parameter [‘your_collection’] serves as a unique identifier for the query. React Query uses this key for caching and re-fetching data.
  • Fetching Function: The second parameter is the function that fetches data from Directus.
  • Response Handling: The useQuery hook returns the data, isError, and isPending states that can be used to manage the UI.

4. Optimising Data with Caching and Revalidation

React Query provides several options to optimise data fetching. For instance, you can set staleTime to define how long the data is considered fresh, and refetchOnWindowFocus to control refetching behaviour.

const { data, isPending, error } = useQuery([‘your_collection’], fetchData, {

  staleTime: 1000 * 60 * 5, // 5 minutes

  refetchOnWindowFocus: false, // Do not refetch on window focus

});

This configuration reduces API requests by preventing frequent refetching while keeping data relatively fresh.

5. Mutating Data with Directus and React Query

React Query’s useMutation hook is perfect for performing data mutations like creating, updating, or deleting items from the Directus API.

import { useMutation, useQueryClient } from ‘@tanstack/react-query’;

const useUpdateItem = () => {

  const queryClient = useQueryClient();

  return useMutation(

    async newItem => {

      await client.request(updateItem ((‘your_collection’), (id),{data}))

    },

    {

      onSuccess: () => {

        // Invalidate the query to re-fetch the updated data

        queryClient.invalidateQueries([‘your_collection’]);

      },

    }

  );

};

The useMutation hook is used to create, update, or delete items, and the onSuccess callback is called to invalidate the query, ensuring the UI is updated with fresh data.

Error Handling in React Query

React Query handles errors gracefully. You can use the isError and error states from useQuery and useMutation to provide feedback to users.

if (isError) return <p>Error: {error.message}</p>;

This allows you to show user-friendly error messages and improve the overall user experience.

Conclusion

By combining Directus with TanStack React Query, you can efficiently fetch and manage data in React applications. Directus provides a flexible and powerful backend for your SQL databases, while React Query simplifies data fetching, caching, and synchronisation. This combination results in a smooth developer experience and a performant, scalable frontend.

React Query’s declarative API, caching mechanism, and built-in handling for stale data and errors make it an excellent choice for integrating with Directus. With this setup, your application will not only be more efficient but also easier to maintain and scale.

Implementing this integration allows you to build modern, data-driven applications with Directus as the backend and React Query as the data management library, enhancing both security and performance in real-time data fetching and updating scenarios.

Susmita Adhikari
Susmita Adhikari

Leave a Reply

Your email address will not be published. Required fields are marked *

This website stores cookies on your computer. Cookie Policy