Lädt...

🔧 Infinite Scrolling of TanStack Query 🌸


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

This article is a continuation of the previous article. So, check that out before you continue.

For infinite scrolling, create an axios function for api calling:

export const getProducts = async ({ pageParam }: { pageParam: number }) => {
  return (
    await axiosInstance.get<Product[]>(
      `products?_page=${pageParam + 1}&_limit=3`
    )
  ).data
}

Now, we need to define an infinite-scrolling specific query:

export function useProducts() {
  return useInfiniteQuery({
    queryKey: ["products"],
    queryFn: getProducts,
    initialPageParam: 0,
    getNextPageParam: (lastPage, allPages, lastPageParam) => {
      if (lastPage.length === 0) {
        return undefined
      }
      return lastPageParam + 1
    },
    getPreviousPageParam: (firstPage, allPages, firstPageParam) => {
      if (firstPageParam <= 1) {
        return undefined
      }
      return firstPageParam - 1
    },
  })
}

Here, we can replace unused parameters with underscores like the following:

getNextPageParam: (lastPage, _, lastPageParam) => {

// -------------------------------------------------

getPreviousPageParam: (_, __, firstPageParam) => {

The properties of useInfiniteQuery are pretty much self-explanatory. Now, implement the infinite query mechanisms in the react component: (This one is long. There will be some explanation after the code)

import { FC, Fragment, useState } from "react"
import { useProduct, useProducts } from "../services/queries"

interface ComponentProps {}

const Products: FC<ComponentProps> = () => {
  const [selectedProductId, setSelectedProductId] = useState<number | null>(
    null
  )

  const productsQuery = useProducts()
  const productQuery = useProduct(selectedProductId)

  return (
    <>
      {/* page data rendered here */}
      {productsQuery.data?.pages.map((page, index) => (
        <Fragment key={index}>
          {page.map((product) => (
            <Fragment key={product.id}>
              {/* click button to see in detail */}
              <button onClick={() => setSelectedProductId(product.id)}>
                {product.name}
              </button>
              <br />
            </Fragment>
          ))}
        </Fragment>
      ))}
      <br />

      {/* button to load to the next page */}
      <div>
        <button
          onClick={() => productsQuery.fetchNextPage()}
          disabled={
            !productsQuery.hasNextPage || productsQuery.isFetchingNextPage
          }
        >
          {productsQuery.isFetchingNextPage
            ? "Loading more..."
            : productsQuery.hasNextPage
            ? "Load More"
            : "Nothing more to load"}
        </button>
      </div>

      {/* selected product in detail */}
      <div>Selected product:</div>
      {JSON.stringify(productQuery.data)}
    </>
  )
}

export default Products

useProducts is used for making pagination api call. So, we get data of the first page and render them initially.

Then, another mechanism is added to select a product and see data in detail. In the rendered page data, there is a button to select, and its data is shown in the bottom. The selected data comes from useProduct api calling. The following is how it works:

// api.ts
export const getProduct = async (id: number) => {
  return (await axiosInstance.get<Product>(`products/${id}`)).data
}

// queries.ts
export function useProduct(id: number | null) {
  const queryClient = useQueryClient()

  return useQuery({
    queryKey: ["product", { id }],
    queryFn: () => getProduct(id!),
    enabled: !!id,
    placeholderData: () => {
      const cachedProducts = (
        queryClient.getQueryData(["products"]) as {
          pages: Product[] | undefined
        }
      )?.pages?.flat(2)

      if (cachedProducts) {
        return cachedProducts.find((item) => item.id === id)
      }
    },
  })
}

Here getProduct is for making the api call.

We call the api through useProduct. this api calling works only when there is an id passed through, as enabled is set to id’s existence.

placeholderData sets cached data when data is being fetched and fills the place with cached data.

...

🔧 Infinite Scrolling of TanStack Query 🌸


📈 50.67 Punkte
🔧 Programmierung

🔧 How to use Infinity Queries (TanStack Query) to do infinite scrolling


📈 50.67 Punkte
🔧 Programmierung

🔧 React-Deep-Dive: TanStack Router und TanStack Query – Teil 2


📈 43.79 Punkte
🔧 Programmierung

📰 React-Deep-Dive: TanStack Router und TanStack Query – Teil 2


📈 43.79 Punkte
📰 IT Nachrichten

🔧 React-Deep-Dive: TanStack Router und TanStack Query – Teil 1


📈 43.79 Punkte
🔧 Programmierung

📰 React-Deep-Dive: TanStack Router und TanStack Query – Teil 1


📈 43.79 Punkte
📰 IT Nachrichten

🔧 Centralizing Query and Mutation Configurations with TanStack Query + React 😎


📈 35.7 Punkte
🔧 Programmierung

🔧 React Query (TanStack Query): Efficient Data Fetching and State Management for React


📈 35.7 Punkte
🔧 Programmierung

🔧 TanStack query or RTK query.


📈 35.7 Punkte
🔧 Programmierung

🔧 TANStack Query: How It Changes the Way You Query APIs


📈 35.7 Punkte
🔧 Programmierung

🔧 Instalación y uso de TanStack Query (antes React Query)


📈 35.7 Punkte
🔧 Programmierung

🔧 Mastering Infinite Scrolling with React Query v5


📈 33.38 Punkte
🔧 Programmierung

🔧 How to Implement React Infinite Scrolling with React Query v5


📈 33.38 Punkte
🔧 Programmierung

🔧 How to Implement React Infinite Scrolling with React Query v5


📈 33.38 Punkte
🔧 Programmierung

🐧 What is your opinion on smooth scrolling vs traditional non smooth scrolling on your favorite apps?


📈 29.79 Punkte
🐧 Linux Tipps

🔧 CodeSOD: Query Query Query


📈 27.62 Punkte
🔧 Programmierung

🔧 Mastering TanStack Query: A Comprehensive Guide to Efficient Data Fetching in React


📈 26.5 Punkte
🔧 Programmierung

🔧 State of React 2024: TanStack Query jetzt beliebter als Next.js


📈 26.5 Punkte
🔧 Programmierung

🔧 Episode 23/51: TanStack Query in Angular, Alex Rickabaugh on Signals


📈 26.5 Punkte
🔧 Programmierung

🔧 Simplify Data Handling in React with TanStack Query and TypeScript!


📈 26.5 Punkte
🔧 Programmierung

📰 State of React 2024: TanStack Query jetzt beliebter als Next.js


📈 26.5 Punkte
📰 IT Nachrichten

🔧 👨🏼‍💻 Building a news app with React Native, Expo Router, and Tanstack Query 📰


📈 26.5 Punkte
🔧 Programmierung

🔧 Bikin Data Handling di React Jadi Gampang dengan TanStack Query dan TypeScript!


📈 26.5 Punkte
🔧 Programmierung

🔧 You DO Need TanStack Query!


📈 26.5 Punkte
🔧 Programmierung

🔧 From Prisma to TanStack Query: Fast Lane to Full-Stack Type Safety


📈 26.5 Punkte
🔧 Programmierung

🔧 React / TanStack Query Series - Part 1 : Introduction


📈 26.5 Punkte
🔧 Programmierung

🔧 TanStack Query 101 with Next.js


📈 26.5 Punkte
🔧 Programmierung

🔧 Using TanStack Query with Next.js


📈 26.5 Punkte
🔧 Programmierung

🔧 Simplifying Data Fetching with Zustand and Tanstack Query: One Line to Rule Them All


📈 26.5 Punkte
🔧 Programmierung

🔧 A Complete Guide to Fetching Data in Next.js with Axios and React-TanStack-Query


📈 26.5 Punkte
🔧 Programmierung

🔧 Can React v19 replace React Query(Tanstack)?


📈 26.5 Punkte
🔧 Programmierung