How to refetch data after create using Prisma in NextJS?

I'm loading data at build time using getStaticProps.

export const getStaticProps: GetStaticProps = async () => {
  const users = await prisma.user.findMany()
  return {
    props: { users }
  }
}

I have a form that creates new data:

const handleSubmit = async ({ name, score }) => {
  const body = { name, email }
  await fetch(`http://localhost:3000/api/users/post`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body)
  }
}    

After submitting a form, I would like to refetch the users to display the new one in real time without reloading the page.

In Apollo Client there's a function called refetchQueries that is here to easily do just that, i.e. re-run the graphQL query whenever the mutation happened. Is there a way to do a similar thing here, using plain NextJs+Prisma without graphQL?


Solution 1:

What you're looking for is Incremental Static Regeneration (ISR)

export const getStaticProps: GetStaticProps = async () => {
  const users = await prisma.user.findMany()
  return {
    props: { users },
    revalidate: 60,
  }
}

You can define a revalidation time per-page (e.g. 60 seconds). The initial request will show the cached page, and when the data gets updated, Next.js will trigger a rebuild with the updated data.