{ DreamFactory: 'Blog' }

Tutorial: Building a React.js app with DreamFactory

Posted by Carsten Jacobsen

Fri, Mar 25, 2016

react.png

ReactJS is getting more and more popular among frontend developers. There are some appealing benefits of ReactJS: It's a lot simpler to work with than larger frameworks like AngularJS, the use of UI components and the Virtual DOM idea is compelling, and it scales well.

React only cares about the UI and doesn't care about the rest of the stack. This makes it perfect for building a web application with DreamFactory as the backend. DreamFactory lets developers take advantage of built-in features like user management, user authentication, SQL and NoSQL data storage, file storage, etc. and focus on building the UI. 

React and DreamFactory together make it easy to get a lightweight, scalable application up and running quickly. Your React application can take advantage of DreamFactory's straightforward REST API, from handling user authentication to storing and retrieving data. 

We've added a React address book application to our list of example applications. The application is similar to the JavaScript Address Book, a simple address book for managing your contacts.

The React Address Book is a simple single-page app based on React and a few React libraries for routing and tables. All the functions used for the DreamFactory REST API requests are extended in the file functions.js, and the code examples show how to use them.

Getting Started

There are two ways to get started with the React sample app. You can import the pre-built package directly from the Apps tab of your DreamFactory instance (in DreamFactory 2.1.1 and higher), or clone the source code from the GitHub repo and follow the build instructions in the README file. In this post, the first approach is described with a walk-through of the steps required to set up your instance.

The code is available at the GitHub repo. To get the app working, just sign up for a free hosted developer account or download the free DreamFactory open source project from Bitnami.

Once you've logged into the DreamFactory Admin Console, follow the steps below to get the address book app up and running.

Step 1: Import the provided application package file:

Screen_Shot_2016-03-24_at_5.25.11_PM.png

After importing the package, the app will be assigned an API Key, which you can see in the Apps tab. This API Key is needed to set up the app. 

twop.png

Step 2: Configure CORS:

Navigate to the Config tab and select CORS. Click the '+' button to add a new CORS entry and select '*' from the list box. This will pre-populate the fields in the form. Enter 3600 for Max Age, make sure that the 'Enabled' checkbox is checked, and save. 

Note: '*' denotes open access to your API endpoints and should only be used in for development.

Step 3: Make files public

The package import installs the app's files in the files/AddressBookForReact folder, and this folder must be made public. Go to the Services tab in the admin console and click the 'files' service. Click the Config tab and add the app folder name 'AddressBookForReact' as a public path. Now select 'local' from the Container drop down. 

Step 4: Configure the application

Now edit the these lines of code in the public/bundle.js file. 

var INSTANCE_URL = '';
var APP_API_KEY = '';

When the React Address Book Sample App code is not running on the DreamFactory 2.x instance, specify the instance host (e.g. http://www.my-instance.com) in INSTANCE_HOST, otherwise leave INSTANCE_URL blank. Insert the app API Key in APP_API_KEY. 

See the readme for more detailed instructions.

Code Example

The React Address Book shows how to log in, log out and perform common CRUD operations. The application uses AJAX to perform HTTP requests to the REST API, and the requests are executed inside ReactJS components.

Let's take a look at a simplified example, where we want to populate an input field with a group's name. The group name is retrieved from the table 'contact_group' with a specific group ID: 

<!DOCTYPE html>

<html>

<head>

</head>
<body>
<div id="content"></div>
...
</body>
</html>

const INSTANCE_URL = 'http[s]://<server-name>';
const APP_API_KEY = '<app key>'

var GroupName = React.createClass({
getInitialState: function() {
return {
groupName: ''
}
},
componentDidMount: function() {
var url = this.props.url;
var key = this.props.apikey;
var groupId = this.props.groupId;
var token = localStorage.getItem('session_token');

$.ajax({
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: url + '/api/v2/db/_table/contact_group/' + groupId,
method:'GET',
headers: {
"X-DreamFactory-API-Key": key,
"X-DreamFactory-Session-Token": token
},
success: function(response) {
this.setState({
groupName: response.name
});
}.bind(this)
},
render: function() {
return (
<div>
<div className="text-center"><h2>{this.state.groupName}</h2></div>
</div>
);
}
});

var groupId = 10;

ReactDOM.render(
<GroupName url={INSTANCE_URL} apikey={APP_API_KEY} groupId={groupId} />,
document.getElementById('content')
);

REST API requests

Now let's take a closer look at how to use the DreamFactory REST API. All requests are formatted like this:

http[s]://<server-name>/api/v2/[<service-api-name>]/[<resource-path>][?<param-name>=<param-value>

All API requests executed from the Address Book are done with AJAX calls, with the following parameters:

dataType: String
contentType: String
url: String
data: String,Object
method: String
headers: Object

Breaking down each parameter:

dataType - format of the returned data. This depends on the application, but will typically be JSON.
contentType - the format of data sent to the API. This is commonly JSON and charset UTF-8.
url - the URL to the REST API endpoint (see format in Code Examples). You can include the query parameters here. However, it is easier and cleaner to pass in the query parameters by using the data parameter than it is to format them into the url.
data - the (optional) query parameter(s).
method - the REST verb (e.g. GET, POST).
headers - the header object must include the app-specific API key and a session token.

Log in

The Address Book implements DreamFactory's built-in user management for easy user creation and authentication. New users can register and existing users can log in to the app.

Remember, if the app is imported into the DreamFactory instance, leave INSTANCE_URL blank. Email and password are typically input fields in the app UI (like in the Address Book app).

var INSTANCE_URL = 'http[s]://<server-name>';
var email = 'my@email.com';
var password = 'mypassword';

POST email and password to the endpoint user/session to retrieve a session token:

$.ajax({
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: INSTANCE_URL + '/api/v2/user/session',
data: JSON.stringify({
'email': email,
'password': password
}),
method: 'POST',
success: function (response) {
// Handle success
},
error: function (response) {
// Handle error
}
});

If the email and password matches a user in the DreamFactory instance, a session token will be returned. This session token is used for API requests requiring authentication, and is added to the request header with the API key like this:

headers: {
"X-DreamFactory-API-Key": APP_API_KEY,
"X-DreamFactory-Session-Token": token
}

Getting Records

After logging in and retrieving a session token, we can go ahead and get some records from the instance database. Let's get all the records in the 'contact_group', which contains the group names and IDs.

$.ajax({
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: INSTANCE_URL + '/api/v2/db/_table/contact_group',
headers: {
"X-DreamFactory-API-Key": APP_API_KEY,
"X-DreamFactory-Session-Token": token
},
method: 'GET',
success: function (response) {
// Handle success
},
error: function (response) {
// Handle error
}
});

Now let's get all contacts from the 'contact' table, but we're only interested in the id, first name, and last name. To select certain fields, add the 'fields' parameter to the url.

$.ajax({
...
url: INSTANCE_URL + '/api/v2/db/_table/contact?fields=id%2Cfirst_name%2Clast_name'
...
});

Note: The parameter value must be URL Encoded.

Instead of getting all contacts, let's get all contact ids belonging to a specific group (group id = 10), by looking up contacts in the 'contact_group_relationship'. In this case we use the 'filter' parameter:

$.ajax({
...
url: INSTANCE_URL + '/api/v2/db/_table/contact_group_relationship?filter=contact_group_id%3D10'
...
});

Parameters (e.g. fields, filter, limits) can be combined in the same API request.

Creating Records

As the last example, a new record is created, and it's very similar to getting a record. Instead of executing a GET request, a POST request is executed to an API endpoint. In this example, a new group named 'My Group' is created.

$.ajax({
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: INSTANCE_URL + '/api/v2/db/_table/contact_group',
data: JSON.stringify({
name: 'My Group'
}),
headers: {
"X-DreamFactory-API-Key": APP_API_KEY,
"X-DreamFactory-Session-Token": token
},
method: 'POST',
success: function (response) {
// Handle success
},
error: function (response) {
// Handle error
}
});

Note: The data must be stringified.

If the API request was successful, and the group was created in the instance database, the id of the new group is returned.

DreamFactory + React

Using DreamFactory as a backend for React applications is easy. We hope this tutorial is helpful and will get you started using DreamFactory and React in your own projects. Feel free to ask questions in the comments or head over to community.dreamfactory.com.

 

Get started with DreamFactory with a free hosted DreamFactory development environment. Or, download and run it on the server, cloud, or desktop of your choice.

DreamFactory Silver React

Weekly Digest

Recent Posts