Quickly setup a persistent React application head

Quickly setup a persistent React application

After having recently picked up the React framework, I figured I’d share how I quickly setup my projects to implement persistence. This way you spend minimal time setting up the skeleton of your application, letting you focus on adding functionality. This is done by combining a few tools. Let’s take a closer look.

Should you be interested in the code itself, go ahead and get it here.

Tools

NPM/Yarn

Be sure to install a package manager like npm or Yarn. We will use it to install and run some of the other tools.

Create-react-app
If you ever worked with React you undoubtedly came across this CLI tool. It is useful for providing the boilerplate code you need for the front-end of your application. Take a look at the documentation to get a sense on how to use it.

FeathersJS
This is an implementation of the Express framework. It provides another CLI tool we can use to quickly setup the boilerplate code for building a REST API. What makes it powerful is the concept of hooks (see this link for more) as well as the possibility to model our entities in a javascript file. After starting this service we can manipulate data in our database using REST calls.

MongoDB
This is the database we will use – be sure to download, install and start it. It’s a NoSQL database and uses a JSON document structure.

Steps
Create a folder for your application with <application name>. I like to create two seperate folders in here. One ‘frontend’, the other one ‘backend’. Usually I will add the source folder to a version control tool like Git. If you’re dealing with a larger application however, you might want to initiate two separate repositories for both your front- and backend. Using Visual Studio Code, my file structure looks like this:

Selection_002

Fire up your terminal. Install create-react-app globally.

npm install -g create-react-app

Navigate to your frontend folder. Initialize your first application.

cd frontend
create-react-app <application name>

Note how the CLI will add another folder with the application name into your frontend folder. Since we already created a root folder, copy the content of this folder and move it one level higher. Now the structure looks like this:

create-react-app

Install FeathersJS CLI globally.

npm install -g @feathersjs/cli

Navigate to the backend folder of your project an generate a feathers application

cd ../backend
feathers generate app

The CLI will prompt for a project name. Follow along with these settings:

feathers-settings

Alright, now it’s time to generate a service so we can start making REST calls. In true Oracle fashion, let’s make a service for the entity employees. While in the backend folder, run:

feathers generate services

Follow along:

feathers-service-settings

Navigate to the employees.model.js file. The filestructure of the backend folder should look like this:

feathers-backend-structure

In this file we can specify what employees look like. For now, let’s just give them the property name of type String and let’s make it required. Also, let’s delete the timestamps section to keep things clean. It should look like this:

//employees.model.js

module.exports = function (app) {
  const mongooseClient = app.get('mongooseClient');
  const { Schema } = mongooseClient;
  const employees = new Schema({
    name: { type: String, required: true }
  });

  return mongooseClient.model('employees', employees);
};

Great. We are almost good to go. First fire up MongoDB. Windows users see here. Unix users:

sudo service mongod start

Next up navigate to the backend folder. Using the terminal, give the following command:

npm start

You should see a message saying: Feathers application started on http://localhost:3030

The service we created is available on http://localhost:3030/employees. Navigate there. You should see JSON data – though right now all you’ll probably see is metadata. By using this address we can make REST calls to see and manipulate the data. You could use curl commands in the terminal, simply use the browser, or install a tool like Postman.

Next up we need a way to access this service in our frontend section of the application. For this purpose, let’s create a folder in the location: frontend/src/api. In here, create the file Client.js.

This file should contain the following code:

//Client.js

import io from 'socket.io-client';
import feathers from '@feathersjs/client';

const socket = io('http://localhost:3030');
const client = feathers();

client.configure(feathers.socketio(socket));
client.configure(feathers.authentication({
  storage: window.localStorage
}));

export default client;

Make sure the libraries we refer to are included in the package.json of our frontend. The package.json should look like this:

{
  "name": "react-persistent-start",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@feathersjs/client": "^3.4.4",
    "react": "^16.4.0",
    "react-dom": "^16.4.0",
    "react-scripts": "1.1.4",
    "socket.io-client": "^1.7.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Be sure to run npm install after updating this file.

That’s basically all we need to perform CRUD operations from our front-end section of the application. To make the example a little more vivid, let’s implement a button into the App.js page which was automatically generated by the create-react-app CLI.

First, I’ll get rid of the boilerplate code in there and I will import the client we just created. Next, create a button that calls method handleClick() when the React onClick method is fired. In here we will call the client, let it call the service and perform a create operation for us. The code will look like this:

//App.js

import React, { Component } from 'react';

import client from './api/Client';
import './App.css';

class App extends Component {
handleClick() {
  client.service('employees').create({
    name: "Nathan"
  });
}

  render() {
    return (
      <div className="App">
        <button onClick={this.handleClick}>Add employee</button>
      </div>
    );
  }
}

export default App;

Navigate to the frontend section in the terminal, make sure the node modules are installed correctly by running npm install. Now use command npm start. Navigate to http://localhost:3030/employees. Verify there is no employee here. On http://localhost:3000 our page should be available and show a single button.  Click the button and refresh the http://localhost:3030/employees page. You can see we have added an employee with the same name as yours truly.

json-result

(I use a Chrome plugin called JSON viewer to get the layout as shown in the picture)

Using the code provided in the handleClick() method you can expand upon this. See this link for all the calls you can make in order to provide CRUD functionality using FeathersJS.

That’s basically all you need to start adding functionality to your persistent React application.

Happy developing! The code is available here.