NextJS 13 Updating Server Component Data – Javascript

by
Ali Hasan
next.js next.js13 reactjs

The Problem:

A developer is using Next.js 13 and facing an issue with updating data in server components. Specifically, changes made to the database are not reflected in the app’s UI unless the page is manually reloaded. Despite setting revalidate to 1 and dynamic to 'force-dynamic' in the fetch function and component file, the data remains outdated. The developer suspects the issue may be related to the Server Action feature, which is still in beta.

The Solutions:

Solution 1: Workaround for Server Component Data Updates

A known issue in Next.js 13 prevents server components from automatically updating data when changes are made to the database.

  1. Workaround:

    • Implement a custom Link component to manually refresh the page when clicked.
      • Import useRouter from next/navigation.
      • Create a refresh prop for the Link component.
      • In the onClick handler, call router.push(href) and then router.refresh().
    • Use the custom Link component in the server component to navigate, passing refresh={true}, which will trigger the page refresh.
    // components/Link.tsx
    import { ComponentProps, forwardRef } from 'react';
    import NextLink from 'next/link';
    import { useRouter } from 'next/navigation';
    
    export default forwardRef<
      HTMLAnchorElement,
      Omit<ComponentProps<typeof NextLink>, 'href'> & {
        href: string;
        refresh?: boolean;
      }
    >(function Link({ href, onClick, refresh, children, ...rest }, ref) {
      const router = useRouter();
    
      return refresh ? (
        <a
          ref={ref}
          href={href}
          onClick={(event) => {
            onClick?.(event);
            if (!event.defaultPrevented) {
              event.preventDefault();
              router.push(href);
              router.refresh();
            }
          }}
          {...rest}
        >
          {children}
        </a>
      ) : (
        <NextLink ref={ref} href={href} onClick={onClick} {...rest}>
          {children}
        </NextLink>
      );
    });
    
    // test/page.tsx
    import Link from '@/components/Link';
    
    <Link refresh href="/">Home</Link>
    

Solution 2: De-Caching

As per [NextJS official documentation][1], fetch requests are automatically cached. To prevent this and update the data without reloading the page, set `revalidate` to `0` while fetching the data. The code snippet below demonstrates this:

“`
const HomePage = async () => {
const res = await fetch('http://localhost:3000/api/meetup', { next: { revalidate: 0 } })
const meetups = res.json()

return (
<>
<MeetupList meetups= />
</>
)
}


[1]: https://nextjs.org/docs/app/building-your-application/data-fetching/caching

Q&A

How to cache data from MongoDB in NextJS 13 page components?

Use fetchCache: skip-cache option to skip caching for fetch requests.

How to Resolve NextJS 13 Server Component Data update issue?

Use provided workaround to avoid automatic caching and force data update.

Video Explanation:

The following video, titled "Refresh a Server Component in Next.js 13 #nextjs #nextjs13 ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

How to refresh the client router cache in the Next.js 13 app router. ⭐ Get my full-stack Next.js with Express & TypeScript course: ...