I need to transition between 2 routes in a NextJs app like the one on the following example:
FROM: /some-route?id=ID_1
TO: /some-route?id=ID_1&page=2
And I have a useEffect
that does something like this:
- Should fire for any
id
change - Makes use of
router.push
for some reason
import { useRouter } from 'next/router';
const { query, push } = useRouter();
const { id } = query;
useEffect(() => {
try {
fetchDataFor(id);
}
catch(err) {
push('/not-found');
}
},[id,push]);
The problem I'm facing with this is related to the fact that the whole router
object will change from the route update, and my effect will re-run because of the push
method reference change, even though my id
is not changing.
I'm currently having to check if the id
has been updated or not by using some useRef
variable that keeps track of the previous value. That's cumbersome.
I thought that maybe I should use a dynamic route, like:
/some-route/[id]
/some-route/[id]?page=2
But I guess the problem will remain, because of the push
property that will keep on changing because of the querystring change.
Another option would be omitting the push
method from the useEffect's dependency array. But that seems like an anti-pattern.
What would be the best approach to solve this issue?
The goal here is being able to use router.push
(or at least be able to push another route somehow) inside the useEffect
that should only run for query.id
updates.