'SWR hook not reflecting database change

This component is for counting views at page level in Next.js app deployed on AWS Lambda

function ViewsCounter({ slug }: { slug: string }) {
  const { data } = useSWR(`/api/views/${slug}`, fetcher);
  const views = new Number(data?.total);

  useEffect(() => {
    const registerView = () =>
      fetch(`/api/views/${slug}`, { method: "POST" })
        .catch(console.log);
    registerView();
  }, [slug]);

  return (
    <>
      {views}
    </>
  );
}

This one is for displaying views on homepage

function ViewsDisplay({ slug }: { slug: string }) {
  const { data } = useSWR(`/api/views/${slug}`, fetcher);
  const views = new Number(data?.total);

  return (
    <>
      {views}
    </>
  );
}

While it works as expected on localhost, looks like it displays only the first fetched value and doesn't revalidate it for some reason.
When visiting the page, Counter is triggered correctly and the value is changed in DB.
Probably it has something to do with mutating, any hints are appreciated.



Solution 1:[1]

useSWR won't automatically refetch data by default.

You can either enable automatic refetch using the refreshInterval option.

const { data } = useSWR(`/api/views/${slug}`, fetcher, { refreshInterval: 1000 });

Or explicitly update the data yourself using a mutation after the POST request to the API.

function ViewsCounter({ slug }: { slug: string }) {
    const { data, mutate } = useSWR(`/api/views/${slug}`, fetcher);
    const views = new Number(data?.total);

    useEffect(() => {
        const registerView = () =>
            fetch(`/api/views/${slug}`, { method: "POST" })
                .then(() => {
                    mutate();
                })
                .catch(console.log);
        registerView();
    }, [slug]);

    return (<>{views}</>);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 juliomalves