Sunday, May 21, 2017

How to use Relay GraphQL node identification with clean URL REST resources id

Relay uses node identification to cache parts of graphql query, but in order to do that we need to use type connections and node IDs.


In React Web App, the user may browse a list of posts and click to show post detail. Or, the user may access a post directly from the url.


In the first scenario, relay fetch a list of posts assign an ID for each node, and when the user click on the show post link, the link should send the node ID for Relay uses it and either 1) retreive the node from the cache or 2) retreive the node from the graphql server using the node interface like on the graphql query above.


In the second scenario the page will be universally rendered by the server and Relay wouldn't have the change to fetch this specific node and hence I wouldn't know the node ID and then I have to fetch the node by any unique attribute like database ID, title or slug.


So the aim of this post is to show how to handle both scenarios in the React App.

The idea is to use the element of react-router to send both the URL ID and the Node ID (if exists) to the Router.



We will create two QueryRenderer component one for each scenario.

And based on the existence of location.state.post_id we can choose which QueryRenderer to use.
In Relay Classic we could get away with one QueryRoute and change the root query based on the presence of Node ID. but in Relay Modern the graphql get precompiled and the root query have a strict naming convention based on the component name so I didn't find another solution except creating two QueryRenderer components.

No comments:

How can you work with a JSON value if you know nothing about it?

I have talked about the difficulty of typing certain JSON values coming from some APIs. The JSON is just very complicated. When I do that,...