You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Tanstack Query+Shadcn数据表新增行时显示Toast弹窗?

解决方案

核心思路

通过保存上一次拉取的数据长度,在每次轮询成功后对比当前数据长度,若长度增加则触发提示弹窗(Toast),同时将数据渲染到shadcn的数据表中。

完整代码示例

import { useQuery } from '@tanstack/react-query';
import { useState, useEffect } from 'react';
// 导入shadcn的Table组件(根据实际项目路径调整)
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
// 导入shadcn的Toast工具(假设使用shadcn默认的toast方案)
import { toast } from '@/components/ui/toast';

export default function ListingsPage() {
  // 存储上一次拉取的数据长度,初始为0
  const [prevDataLength, setPrevDataLength] = useState(0);

  const {
    isLoading,
    error,
    data: listingsData,
    isSuccess, // 用于判断是否拉取成功
  } = useQuery({
    queryKey: ['listingsData'],
    queryFn: () =>
      fetch(`${process.env.baseUrl}/test`).then((res) => res.json()),
    refetchInterval: 2000,
    retry: 5,
  });

  // 监听数据变化,判断是否有新增项
  useEffect(() => {
    if (isSuccess && listingsData) {
      const currentLength = listingsData.length;
      // 排除首次加载的情况,仅当历史长度不为0且当前长度更大时触发提示
      if (currentLength > prevDataLength && prevDataLength !== 0) {
        const newItemCount = currentLength - prevDataLength;
        toast({
          title: '数据更新',
          description: `新增了${newItemCount}条数据`,
        });
      }
      // 更新历史长度为当前长度
      setPrevDataLength(currentLength);
    }
  }, [isSuccess, listingsData, prevDataLength]);

  // 加载状态处理
  if (isLoading) return <div>加载中...</div>;
  // 错误状态处理
  if (error) return <div>加载失败:{(error as Error).message}</div>;

  return (
    <div className="container mx-auto p-4">
      <h1 className="text-2xl font-bold mb-4">数据列表</h1>
      {/* shadcn 数据表渲染 */}
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              {/* 替换为你的实际数据字段 */}
              <TableHead>ID</TableHead>
              <TableHead>名称</TableHead>
              <TableHead>创建时间</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {listingsData.map((item: any) => (
              <TableRow key={item.id}>
                <TableCell>{item.id}</TableCell>
                <TableCell>{item.name}</TableCell>
                <TableCell>{item.createdAt}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}

关键细节说明

  • 历史长度存储:用useState保存prevDataLength,初始值设为0,避免首次加载数据时误触发提示。
  • 新增判断逻辑:在useEffect中监听isSuccess和listingsData的变化,仅当拉取成功且当前数据长度大于历史长度时,才触发Toast提示。
  • shadcn数据表集成:直接使用shadcn的Table组件遍历数据渲染,需根据你的实际数据结构调整字段和渲染逻辑。
  • Toast触发:调用shadcn的toast函数,根据新增数据的数量显示对应提示内容。

注意事项

  1. 确保已正确安装并配置@tanstack/react-query、shadcn的Table和Toast组件。
  2. 如果API返回的不是数组格式,需要先将数据转换为数组再进行长度对比。
  3. 若数据有唯一标识,也可以通过对比新旧数据的唯一ID集合来判断新增,比单纯对比长度更精准(适合数据可能删除的场景)。

内容的提问来源于stack exchange,提问作者arena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 02:22:29