⚠️ This lesson is retired and might contain outdated information.

Routing between Dynamic Routes in Nextjs

Domitrius Clark
InstructorDomitrius Clark
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 2 years ago

After setting up some base routes and defining some endpoints, we can use Nextjs's Link component and useRouter to link back and forth between your defined routes. We can pass in variables to our dynamic routes and use that to call specific endpoints for our data.

Domitrius Clark: [0:00] Back in our singular user component, we'll import our useQuery and our fetch again.

[0:13] Down we'll define our useQuery. We'll destructure data and status. We'll define an array queryKey with a cache key of user and an id variable. Then we'll define our asynchronous fetch function. We'll grab the key and the id. We'll define a constant of user and await our fetch to our /api/user/${id}. Then we'll return the user.json.

[0:50] Per usual, we'll check to see if the status is loading and return our "Loading ..." tag. Replace our old return with a new one. We'll return a div. We'll check to make sure that data isn't undefined and then return some JSX. We'll use a fragment here.

[1:17] We'll render a button so that we can go back from where we came, onClick. We'll use our router.back functionality so that anywhere that we came from the router already knows. We'll let the router decide where back is. We then can take the id, the name, and the email and put those all on <p> tags.

[1:47] Hit Save and head on over to the browser. We'll click Domitrius first. You'll see we're getting all of our information. We can go back. Dan. Go back again. Anna. Fantastic.