Reputation: 1
I have an application where I want to redirect the user to a page containing the first result of a array of data once is it fetched.
For example:
What I am doing right now:
const {data, isLoading} = useGetToto();
useEffect(() => {
if(data?.results.length > 0) {
router.push(`/toto/${data?.results[0].id}`
}
}, [data])
if(data?.results.length === 0)
return <p>No content yet</p>
return <p>Loading...</p>
I wonder if there is a better way to do this. Using a useEffect
is probably a bad practice.
Upvotes: 0
Views: 58
Reputation: 2607
The best solution would be to add correct links to navigation. So you will need to check if page has only one result and display link to the result instead. But this a lot depends on your backend - can you do that efficiently (without doing a lot of requests or fetching a lot of data).
The second solution is in your example, you redirect using useEffect
. The only thing I recommend is using router.replace
. Cause in your case you create new browser history entry, so if you click back in the browser, your page with single entry will be rendered and again useEffect
is triggered. And if you use router.replace
, instead of creating new browser history entry, it will replace listing page with entry page url (so back actions will go 2 pages back).
Upvotes: 1