Search code examples
relayjs

How to tell the user to log in with relay?


Almost all of my graphql objects require that the user is authenticated to access them. If the user is not logged in, or their credentials are invalid, the server returns an error with a flag requireLogin set to true.

How can I intercept errors wherever they occur in Relay, capture this specific error, and then use it to update my state in redux (which will then show a message and a login box)?

The ideal place seems to be the NetworkLayer, but before I implement my own custom NetworkLayer is there a better existing solution (some sort of Relay-wide onError handler for example)?


Solution

  • You're likely looking for the renderFailure prop on your Relay Root Container. This gives you a place to handle errors that occur while fetching your data. If you're looking for errors directly relating to Relay Mutations, you can provider success and error handlers to Relay.Store.commitUpdate. I think those two should be capable of handling most scenarios.

    You did mention using Redux along with Relay. I've not done any research into OSS projects combining these two tools, but Relay itself handles a lot of what Redux also handles and more. While Redux is great, I do think Relay is a more custom fit for GraphQL itself, and React, and I've not felt the need to find a spot for Redux in this stack, yet. It might complicate things.