Top

Next.js Documentation

Fastkart offers stunning and one-of-a-kind website demos tailored to your grocery, bakery, and online store needs. With Fastkart, you'll find everything you require to craft the ideal website for your business. Fastkart - your all-in-one solution!

TanStack Query: Declarative data fetching for Next.js

TanStack Query is a powerful data fetching library that makes it easy to manage asynchronous data in your Next.js applications. It provides a number of features that can help you improve the performance, maintainability, and developer experience of your applications, including:

    • Caching
    • Stale data prevention
    • Optimistic updates
    • Mutations

Overall, TanStack Query is a powerful and flexible data fetching library that can help you improve the performance, maintainability, and developer experience of Fastkart-Next.

Here are some specific reasons of why we used TanStack Query in Fastkart-Next.js

    • Fetching user data from a backend API on login
    • Fetching product data from a backend API
    • Fetching real-time data from a backend API for a dashboard application
    • Optimistically updating a shopping cart after adding an item to it
    • Invalidating cached data after submitting a form

Here is an example of how our theme uses the Tan stack query for data fetching.

"use client";

import {Hydrate,QueryClient,QueryClientProvider} from "@tanstack/react-query";
import { useState } from "react";
import SubLayout from "./SubLayout";

const MainLayout = ({ children }) => {
  const [queryClient] = useState(() => new QueryClient());

  return (
    <QueryClientProvider> client={queryClient}>
      <Hydrate state={children.dehydratedState}>
        <NotificationData children={children} />
      </Hydrate>
    </QueryClientProvider>
  );
};

export default MainLayout;   

// NotificationData Component

import Loader from "@/layout/Loader";
import request from "@/utils/axiosUtils";
import { NotificationAPI } from "@/utils/axiosUtils/API";
import { useQuery } from "@tanstack/react-query";

const NotificationData = () => {
  const { data, isLoading } = useQuery({queryKey: [NotificationAPI],queryFn: () => request({ url: NotificationAPI }),{enabled: true,refetchOnWindowFocus: false,select: (res) => res?.data?.data,}});
  if (isLoading) return <Loader />;
  return (
    <ul className="notification-list">
        {data?.map((elem, i) => (
          <li className={!elem?.read_at ? "unread" : ""} key={i}>
            <h4>{elem?.data?.message}</h4>
          </li>
        ))}
    </ul>
  );
};

export default NotificationData;