arena
arena

Reputation: 378

Tanstack Query + Shadcn - How to show a toast msg if a new row is added to my datatable

I'm fetching and polling an external Api with Tanstack Query and showing all the data in a datatable (shadcn). I want to show a toast msg on my page every case if a fetch is successful and a new item appeared in the data. (data length is increased). I'm new with Tanstack, any idea would be appreciated!

  const {
    isLoading,
    error,
    data: listingsData,
  } = useQuery({
    queryKey: ['listingsData'],
    queryFn: () =>
      fetch(`${process.env.baseUrl}/test`).then((res) =>
        res.json()
      ),
    refetchInterval: 2000,
    retry: 5,
  });

Upvotes: 0

Views: 871

Answers (2)

PRSHL
PRSHL

Reputation: 1443

Remember your previous data length and then compare the current length to the old one. If it is higher then fire your toast.

const [previousLength, setPreviousLength] = useState<number | undefiend>(undefined);

// ... your useQuery hook

useEffect(() => {
  if (previousData !== undefined && listingsData.length > previousLength) {
    // FIRE YOUR TOAST
  }
  setPreviousLength(listingsData.length)
}, [listingsData.length, previousLength]);

Upvotes: 0

Ahmed Abdelbaset
Ahmed Abdelbaset

Reputation: 4936

First we need to save the latest items.

const previousItemsIds = useRef([]);

Then let's compare the new data with previous data

const previousItemsIds = useRef([]);

const {
  isLoading,
  error,
  data: listingsData,
} = useQuery({
  queryKey: ['listingsData'],
  queryFn: async () => {
    const items = await fetch(`${process.env.baseUrl}/test`).then((res) =>
      res.json()
    );

    if (itemsIds.length === 0) {
      // this is the first time data is fetched. let's save the data for later
      previousItemsIds.current = items;
    } else {
      const newItemsIds = data.map(item => item.id) // we need any unique value. mostly it's `id`

      // if there is new items:
      const isNewItem = newItemsIds.some(id => previousItemsIds.current.includes(id) === false);

      if (isNewItem) {
        toast("There is a new item")
        // let's save the latest changed items
        previousItemsIds.current = newItemsIds
      }
    }
   
  },
  refetchInterval: 2000,
  retry: 5,
});

Upvotes: 1

Related Questions