Using next/router with SWR and fallback data (pages router)
Unanswered
Boxed posted this in #help-forum
BoxedOP
Hi,
I'm using Next.js 13.3.4 with the pages router.
I have a page that fetches data server-side using
The page has a button that can be clicked to navigate to a certain route by calling
Originally, this page only used server-side data passed down as props from
The page is at a dynamic route (such as "/pages/item/[id]/index.tsx")
Here's an example of what the page essentially looks like: https://gist.github.com/suvanl/9a0bb0a5fda79fa69f27182a9d34e526
I've linked it as a Gist since it is too long to include in this post.
I have tried using a
Namely, the error that I'm getting points to the line where
Also, the URL in the browser does change to "/home", but the error on ItemPage occurs and results in the contents of "/home" not being rendered.
So it looks like the issue is that
I'm using Next.js 13.3.4 with the pages router.
I have a page that fetches data server-side using
getServerSideProps. This data is used as fallback data. From then on, data is kept up-to-date on the client-side using the useSWR hook. The page has a button that can be clicked to navigate to a certain route by calling
router.push("/my/route") on click. However, when the button is clicked and this function is called, a rerender seems to occur, and this results in an unhandled runtime error since the data becomes null when the page is rerendered. Originally, this page only used server-side data passed down as props from
getServerSideProps, and this functionality worked fine. Ever since implementing SWR, this issue has started to occur.The page is at a dynamic route (such as "/pages/item/[id]/index.tsx")
Here's an example of what the page essentially looks like: https://gist.github.com/suvanl/9a0bb0a5fda79fa69f27182a9d34e526
I've linked it as a Gist since it is too long to include in this post.
I have tried using a
<Link> instead, but the same issue persists.Namely, the error that I'm getting points to the line where
dataSource is declared (line 26), since dataSource is undefined on the rerender (I assume since no data was re-fetched). The full error is: "TypeError: Cannot read properties of undefined (reading 'features')".Also, the URL in the browser does change to "/home", but the error on ItemPage occurs and results in the contents of "/home" not being rendered.
So it looks like the issue is that
dataSource is undefined whenever router.push() is called - why does this happen, and how could it be fixed? If the data truly is undefined, I want it to redirect to "/error", as seen inside getServerSideProps. However, this redirect never happens. Even if I were to add a client-side check for this, it would involve calling router.push() if the data is indeed undefined, and that's what's causing my issue (seemingly).