Client-Side Data Fetching Example useQuery

Marickian
By -
0
Client-Side Data Fetching Example

Data Fetching and Display in a Client-Side Component

In modern web applications, especially with frameworks that support server-side rendering (SSR) and client-side rendering (CSR), it's common to fetch data both on the server and in client components. In this article, we'll explore how to set up a simple client component that fetches data and renders it dynamically.

Setting Up the Component

First, we need to create a client component where we can fetch and display data dynamically. We'll use a useQuery hook to manage the data fetching process.

        
const MyClientComponent = () => {
    "use client";

    const { data, isPending } = useQuery({
        queryKey: 'dataKey',
        queryFn: fetchDataFunction
    });

    return (
        <div>
            {isPending ? (
                <span className="loading">Loading...</span>
            ) : (
                <DataListComponent data={data} />
            )}
        </div>
    );
};
        
    

In the code snippet above, we define a basic component that uses a useQuery hook to fetch data. The hook manages both the loading state and the actual data. When the data is still being fetched, we display a loading message. Once the data is fetched, we pass it to the DataListComponent for rendering.

Handling Loading States and Conditional Rendering

A key part of working with client-side data fetching is managing the loading state. In our example, we check the isPending flag to determine whether the data is still being fetched. If it's true, we show a loading spinner or message. Otherwise, we display the fetched data.

        
{isPending ? (
    <span className="loading">Loading...</span>
) : (
    <DataListComponent data={data} />
)}
        
    

Rendering the Data

Once the data is fetched, we need to render it in a structured format. Here, we loop through the fetched data and display each item inside a card component. If no data is found, we show a fallback message.

        
const DataListComponent = ({ data }) => {
    if (!data || data.length === 0) {
        return <h4>No items found...</h4>;
    }

    return (
        <div className="grid-layout">
            {data.map((item) => (
                <div className="card" key={item.id}>
                    <h2>{item.title}</h2>
                    <p>{item.description}</p>
                </div>
            ))}
        </div>
    );
};
        
    

In this example, if there is data, we map over it and render each item in a card format. If no data is available, a message stating "No items found" is displayed instead.

Why Multiple Query Instances?

You might wonder why we need multiple instances of the useQuery hook in certain cases. For example, if we have a search functionality, we might need to trigger data fetching multiple times with different parameters. Each instance of the useQuery allows us to fetch data for different conditions (e.g., with or without search terms).

        
const { data, isPending } = useQuery({
    queryKey: ['dataKey', searchTerm],
    queryFn: () => fetchDataFunction(searchTerm)
});
        
    

Here, we use the search term as part of the query key to differentiate between various search results.

Final Thoughts

Client-side data fetching with hooks like useQuery provides a flexible and efficient way to manage state in web applications. By properly handling loading states, errors, and conditional rendering, you can create a smooth user experience where data is loaded dynamically and efficiently.

Post a Comment

0Comments

Post a Comment (0)