Search code examples
reactjsroutesnext.jsserver-side-renderingnext-router

How to prevent getServerSideProps from running again when pushing query param?


I'm asking because I don't know exactly what to do. When my page is loaded, I have a table yield that I got from the API with getServerSideProps. Like this:

export const getServerSideProps: GetServerSideProps<Props> = async (
  context
) => {
  const { query } = context
  const { limit, offset } = query

  const reqData = await axios({
    method: 'POST',
    url: 'http://localhost:3000/api/kurbanlik',
    data: {
      limit,
      offset,
    },
  })
  const { data, total } = await reqData.data

  return {
    props: {
      data, // Hayvan Data (All Rows)
      total,
      query,
    },
  }
}

My table rows are based on this data. When I onRowClick any of the table rows, the page is redirected with router.push id query params. For ex. localhost:3000/?id:102112. When I click on each row, the modal component specific to that row opens. And change id query params.

But I have a problem. When I click on each row, all the table data I got from the getServerSideProps is called again. I only need to do this when the first page is rendered.I don't need it to recreate the table data over and over.

How can I prevent this?


Solution

  • Use shallow: true in the router.push call to prevent getServerSideProps from running again.

    From the Shallow Routing documentation:

    Shallow routing allows you to change the URL without running data fetching methods again, that includes getServerSideProps, getStaticProps, and getInitialProps.

    router.push('/?id=102112', undefined, { shallow: true })