React + Low-code backend. The way to skip infrastructure messing up
Tags: tutorial, react, webdev, database
Published: 2020-05-30 13:45:50

Hey all! Almost any web app needs both a frontend and a backend parts. React seems to be the best choice for building a user interface. It's clean, flexible and fast. From my experience, development often *gets stuck due to the backend* part. It takes too long to setup a database, update API-methods, configure RBAC and mess up with an infrastructure. 

There is a way how to make it simpler. I'd like to show you the process of developing a React app with backend based on [Directual](https://directual.com)—the visual backend constructor. First, I'll give the general approach overview. Then, you'll find the full [live-demo](#live-demo) of development (I've built this example app: [MyMovieList](https://mymovielist.directual.app/) in 2h 53m). The video may also be considered as a tutorial for beginners.

## General overview
![React-Directual](https://api.alfa.directual.com/fileUploaded/directual-site/fa250115-523b-441d-ac08-8a33a4feb12e.png)

### User Interface
Feel free to develop your UI as you like–with hooks, classes, etc. Having connected Directual backend you can use the following patterns:

```javascript
import Directual from 'directual-api';
import { useAuth } from '../auth' // we will look at auth.js further in post
//...
const api = new Directual({ apiHost: '/' })
const auth = useAuth();
//...
const dataStructure = '' // todo: insert here Sysname of your data structure
const endpoint = '' // todo: insert here Method name of your API-endpoint
//...
// Auth context:
auth.user // returns user ID
auth.sessionID // returns user session ID
auth.isAutorised() // returns true if user is authorised
auth.hasRole('role') // returns true if user.role == 'role' (see user management further)
//...
// GET request:
function getData() {
    api
      // Name of Data structure (table) in the Database
      .structure(dataStructure)
      // GET request + query params (sessionID)
      .getData(endpoint, { sessionID: auth.sessionID})
      // other possible query params: page, pageSize, sort and any custom parameter for Filtering
      .then((response) => {
        // handling response
      })
      .catch((e) => {
        // handling errors
      })
  }
//...
// POST-request:
let payload = {} // Request payload
function postData() {
    api
      // Name of Data structure (table) in the Database
      .structure(dataStructure)
      // POST request + payload + query params
      .setData(endpoint, payload, { sessionID: auth.sessionID })
      .then((response) => {
        // handling response
      })
      .catch((e) => {
        // handling errors
      })
  }
//...
```

### Low-code cloud backend
Let's figure out how we can setup database, backend logic and APIs on Directual. You can use the platform for free. There are limits on the load produced by an app in free plan (10k requests per month).

**Database**
Here it is—a UI for managing database. Folders and tables (data structures):
![Directual database](https://api.alfa.directual.com/fileUploaded/directual-site/a4437660-9a7b-42ad-be91-e9fc60a6ba59.png)
This is the page for configuring a table (data structure):
![Directual database, Configuring fields](https://api.alfa.directual.com/fileUploaded/directual-site/f87963cd-4f7e-4fb5-9331-a93c85eab627.png)
Also, there is a system structure – **App users** (system name `WebUser`). Its objects are users. These objects from `WebUser` have the following properties: `id` (username), `password`(encrypted) and `role`:
![App user](https://api.alfa.directual.com/fileUploaded/directual-site/5c50ed33-016c-443f-bbfe-6d9b3acab0bc.png)

**API-builder**
Go to section API, and here you can configure API-endpoint:
![API-endpoint](https://api.alfa.directual.com/fileUploaded/directual-site/f1b3626d-3b60-4836-9394-5461adf0a3c9.png)
Setting up an API method we can add user-based security, filters and sorting. Also we can indicate which fields will be available for GET- and POST-requesting.

**Backend logic (scenarios)**
There are workflows (*Directual scenarios*) for processing the data (both in real-time and in scheduled manner). Basic scenario steps are just actions under objects, so these steps are quite universal.
![Directual scenario](https://api.alfa.directual.com/fileUploaded/directual-site/927fb359-d5ed-4fdb-b6be-ad8c9a8ba161.png)

### Directual React module
There are two useful files from [Directual React Boilerplate](https://github.com/directual/directual-react-boilerplate):
[auth.js](https://github.com/directual/directual-react-boilerplate/blob/master/src/auth.js) provides methods: `.user`, `.sessionID`, `.isAutorised()`, `.hasRole()`.
[setupProxy.js](https://github.com/directual/directual-react-boilerplate/blob/master/src/setupProxy.js) creates middleware proxy to `directual-api`, for resolving the problem linked with CORS. We need to `install http-proxy-middleware`.

Also you need to edit the `.env` file for connecting with Directual app:
`APP_ID=_YOUR_APP_ID_`

You can find (or create) your App ID in API section:
![api-key](https://api.alfa.directual.com/fileUploaded/directual-site/ba670c8d-e682-4ac6-b6b4-38ecc4301b0e.png)

## Live-demo<a name="live-demo"></a>

### The idea of the example app
I wanted my friends to be able to recommend me movies. So, the app solved that problem. There are 'watched' and 'to watch' movie lists and the form for submitting a recommendation (signing in is required). The result is here [MyMovieList](https://mymovielist.directual.app/), find its code [on GitHub](https://github.com/paveler/mymovielist). 

### We'll cover:
- Bootstrapping React app based on Directual [boilerplate-code](https://github.com/directual/directual-react-boilerplate);
- Using React hooks for handling state;
- Building authentication and private routing;
- Configuring database and required APIs in Directual;
- Getting/Posting data from/to the database;
- Connecting a third-party API for enriching data;
- Building and packing our product into Docker container.

I've recorded the whole development process. It took 2 hours 53 minutes, without any fuzz. Have a look! I tried to compose it as a tutorial for beginners. I didn't cut anything. If you are an experienced frontend-dev, you may consider watching all the details a bit boring, so, use the timestamps on Youtube. :)

{% youtube vVZD1AeQZFE %}

### What's next
If you, guys, like such a live-tutorial, I can compose more—this simple site may be be developed into movies-related social network with profiles, individual lists, likes, shares, etc. It will be a good exercise. I suppose, it'll take a couple of hours more.