Next.js Discord

Discord Forum

Redirecting during render causing `Cannot update a component while rendering a different component`

Answered
Tomistoma posted this in #help-forum
Open in Discord
TomistomaOP
I'm building out a form system with two routes:
- /form which is the starting page
- /form/[id] which shows page number id of the form.
I have a component FormPageRouter, which is inside the page.tsx of the /form/[id] route. It takes the id and displays the given page from that id. It also does some validation beforehand and if it fails it redirects you.
- if the id is not a number it redirects back to /form
- if the id is not a valid page it redirects back to /form
- if the user tries to jump to a page ahead of the one they are on, they are redirected back to the current page. for example, if they are on /form/2 and they go to /form/5 (assuming 3, 4, 5, are not completed), it will redirect back to /form/2.
The component basically looks like this:
const FormPageRouter: React.FC<Props> = ({ params }) => {
  const router = useRouter();

  if (params.id is not number) {
    router.replace("/form");
    return <></>
  }

  // too large/too small
  if (params.id is invalid id) {
    router.replace("/form");
    return <></>
  }
  
  // gets saved data from localStorage and loops
  // to find the first page that was not fully completed
  if (params.id is not completed) {
    router.replace(`/form/${first_uncompleted_page}`);
    return <></>
  }

  return (
     <FormPage
        data={...}
        id={...}
      ></FormPage>
  )
}

However, hitting any of these redirects causes a status 500 error to be returned from the previous url and the error:
Cannot update a component (`Router`) while rendering a different component (`FormPageRouter`)

I'm not exactly sure if it's recommended to redirect during render like this? what I found online does not target the app router and uses getServerSideProps to redirect.
doing it like this also causes a brief flash of an empty page. I cant find too much about dynamic redirects when using the app router so I would like to know is there a better way of doing this?
Answered by Tomistoma
because of other issues I ended up putting everything in a useState with no dependencies and just showing a loading screen in the downtime between redirecting or showing the form page. this has gotten rid of the error now
View full answer

1 Reply

TomistomaOP
because of other issues I ended up putting everything in a useState with no dependencies and just showing a loading screen in the downtime between redirecting or showing the form page. this has gotten rid of the error now
Answer