REST (HATEOAS) and ReactJS

Brent Arias picture Brent Arias · Mar 5, 2016 · Viewed 7.1k times · Source

I'm interested in using the HATEOAS principle of REST to reduce business logic in a SPA application. In a React-specific context, I'd like to know if there are challenges that make this impractical and, if not, what is a good strategy to follow?

Conceptual examples of using HATEOAS to remove business logic from the UI:

I've only found one link that suggests React/Flux is not compatible with a HATEOAS strategy, and no meaningful discussion elsewhere. Is it really not feasible in a React/Flux app? That SO post didn't get enough attention. Does anyone have a favorite or recommended approach for achieving success (with or without Flux or Redux)?

Someone gave a fairly detailed example of leveraging HATEOAS in the context of Angular. I'm looking for something similar for React.

Personally, I'm picturing the rel tag in hypermedia links controlling which JSX components are rendered (conditional JSX). Is that naive for a real-world React app? Perhaps conditionally rendered React components are too coarse-grained to be used this way?

I am assuming that hypermedia links are provided by a HAL implementation, or otherwise conform to the ATOM feed convention (RFC4287).

Answer

shenku picture shenku · Oct 27, 2016

100% HATEOAS IS compatible with React & Flux, HATEOAS is compatible with Angular, HATEOAS is compatible with JQuery and even vanilla JS.

HATEOAS doesn't not impose any technical or implementation requirements on a consuming client.

HATEOAS is in fact simply a concept to which you can design your API (you can use one of several standards though like HAL)

Basically if you can call an API then you can implement a HATEOAS client.

So how to get there:

  • Step 1, how would you normally do an API call in React? Do it the same way.
  • Step 2, interrogate response.
  • Step 3, based on response, respond in the UI appropriately.

For example given a call to the order api /orders, I get the following response:

{
    "_links": {
        "self": { "href": "/orders" },
        "next": { "href": "/orders?page=2" }
    }
}

From this I can infer that next is a valid relation, and that if I go to that href I would in fact receive a second page of orders, so in this case in the UI show the next button.

However if I had received the following response:

{
    "_links": {
        "self": { "href": "/orders" },
    }
}

Then I could infer that next is not a valid relation, and in my UI I should disabled or not display a next button.

There is no magic, it is simply a change in thinking, a new paradigm.