Thursday, August 8, 2019

React Router v4 Tutorial - #5 Nested Routes

We've already come across nested routing when building out the writer's details page. In this video, I decided to go further and explore deeply nested routes. Our app currently features authors, but it would be useful to also know about the works that they had produced. For that, we'll set up a "texts" resource in our data store referring to the books or publications.

Note that we'll keep the JSON tree flat and have books on the same level as writers, as opposed to nesting the "texts" attribute under each individual writer node. This pattern is known as denormalization; Firebase docs do a good job at explaining why it's preferred over deeply-nested structures text or book was written by an author, hence the relationship between the two is such that a writer has many books. In other words, "texts" is a children resource of "writers". That's great, but Alex, how do we create an association between the two? Well, we don't, you silly goose! Turns out, json-server already features a mechanism to tie these two together. All we need is a "writerId" property on each text object, and voilà, the two are linked up!

To verify, you can issue a GET on /writers?_embed=texts. Notice the _embed query param; it instructs json-server to include a given child resource in the payload. In this example, each writer will also have a "texts" attribute holding an array of books each with its corresponding writerId. The upshot is that now, not only do we have a listing of writers, but also a catalog of the books that they'd written! Moreover, we can also POST to /writers/{writerId}/texts to create a new book resource, and json-server will infer "writerId" from the URI path and pre-populate it, how cool is that?

When it comes down to React Router, adding an extra nested route is trivial. A Route component can go straight into the Writer file. We'll loop through the books and list a link to each, then render a Text component to show the book details (title, description, you name them). From then on, it's easy-peasy. In the next episode, we'll connect the app with Material-UI.

Don't forget to sync up your store.json with mine, here's the link (And yes, I compiled the list by hand, why not pay the dues to the greatest writers and thinkers of all time!)

Relationships in json-server

No comments:

Post a Comment