Database Client Documentation
This document outlines the setup and usage of our database client, which utilizes Supabase (opens in a new tab) for database operations and React Query (opens in a new tab) for state management.
Technologies Used
- Supabase Client (opens in a new tab): Used to connect to the Supabase database and perform CRUD operations.
- React Query (opens in a new tab): Employed for efficient state management and data fetching.
Project Structure
The database client implementation is organized into three main directories:
src/lib/db/models
: Contains files defining database models.src/lib/db/repository
: Contains files defining database operations.src/hooks/<feature>
: Houses files that create React Query hooks for data fetching.
Database Operations
Database operations are defined in the src/lib/db/repository
directory. Each file in this directory corresponds to a specific data entity or table.
Example: Product Operations
File: src/lib/db/repository/product.ts
import { supabase } from '@/lib/supabase';
export const getProducts = () => {
return supabase.from('data').select(`
*,
data_categories (
categories (name)
)
`);
};
This example demonstrates a read operation to fetch products from the 'data' table, including related category information.
React Query Hooks
React Query hooks are created in the src/hooks/product
directory. These hooks utilize the database operations defined in the repository files.
Example: Product Hook
File: src/hooks/product/useProducts.ts
import { useQuery } from '@tanstack/react-query';
import { getProducts } from '@/repository/product';
export const useProducts = () => {
return useQuery({
queryKey: ['products'],
queryFn: async () => await getProducts(),
});
};
This hook uses React Query to manage the state of product data fetching.
Usage
To use the database client in your components:
- Import the appropriate hook from the hooks directory.
- Use the hook in your component to fetch and manage data.
Example:
import React from 'react';
import { useProducts } from '@/services/product';
const ProductList = () => {
const { data, isLoading, error } = useProducts();
if (isLoading) return <div>Loading...</div>;
if (error) return <div>An error occurred: {error.message}</div>;
return (
<ul>
{data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
};
export default ProductList;