#swr revalidation

1 messages · Page 1 of 1 (latest)

wanton crater
#

I'm having an issue where my swr based fetch is not being revalidated even when page is refreshed.

"use client";
import { Loader2 } from "lucide-react";
import useSWR from "swr";
export default function ViewCount(props: { id: string }) {
  const fetcher = async (url: string) => {
    const res = await fetch(`${url}?timestamp=${new Date().getTime()}`, {
      cache: "no-store", // Ensure no caching by fetch API
    });
    if (!res.ok) throw new Error("Network response was not ok");
    return res.json();
  };
  const { data, error, isLoading, isValidating } = useSWR(
    `/api/vehicles/${props.id}/views`,
    fetcher,
    {
      revalidateOnFocus: true,
      revalidateOnReconnect: true,
      refreshInterval: 30000, // Set to 0 to disable automatic interval revalidation
    }
  );

  if (error) {
    console.error(error);
    return <div>Error</div>;
  }

  return (
    <div>
      <span className="flex gap-2">
        <span>Views:</span>
        {isLoading || isValidating ? (
          <Loader2 size={20} className="animate-spin" />
        ) : (
          data?.views
        )}
      </span>
    </div>
  );
}

even with the timestamp in the URL, it still returns the same value every time in the response

green hollowBOT
#

Hi @wanton crater. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the knowledge sources provided, there isn't specific information about SWR revalidation. However, there are some related discussions about revalidation in Next.js, which might be helpful.

In Next.js, if an error is thrown while attempting to revalidate data, the last successfully generated data will continue to be served from the cache. On the next subsequent request, Next.js will retry revalidating the data source (https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#error-handling-and-revalidation).

There are also some discussions about issues with revalidation in Next.js on GitHub. For example, one issue discusses a problem where revalidation is using stale data source (https://github.com/vercel/next.js/issues/58909). Another issue discusses a problem where on-demand revalidation doesn't work for pages that are pre-rendered during build time source (https://github.com/vercel/next.js/issues/59883).

However, these discussions are about revalidation in Next.js, not specifically about SWR. For more specific information about SWR revalidation, you might want to check the SWR documentation or ask in a community where SWR is discussed.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: