In my React application, a Route in the nav menu points to /persons url. When clicked, the rendered page shows all the available persons, let's say in a table. The user can then select a particular person to see the detail at the url /persons/:personId. However, when there is only one user available, the requirement is to directly show the person detail, and bypass the step to show table of persons.
In the React Component, I am trying to identify if there is only one person available in the useEffect() and using react-router-dom's navigate(useLocation().pathname + "/" + personId).
Here is the relevant code snippets.
...
<Route path="/persons/:personId?" element={<Persons />} />
...
const { personId } = useParams();
const persons = // via some service call;
useEffect(() => {
if (!personId && persons.length === 1) {
useNavigate()(useLocation().pathname + "/" + persons[0].id);
}
}, []);
...
With this I receive => 'Too many re-renders. React limits the number of renders to prevent an infinite loop.'
Here are my questions
- How to navigate to the same page having added a parameter from within the page?
- What is the best practice around this use-case? Should I render another component for /persons/:personId?