Skip to main content

How to build a Collaborative Web App With PubNub.


PubNub Reactjs Stickie Web App


In this tutorial, you will be shown  how to use PubNub to build a real-time collaborative web app using React.js, which lets you manipulate the DOM very efficiently, and the next generation of JavaScript, ES6.
I have created two versions of the same Stickie Note app: the one I hosted on this CodePen uses CDN-hosted versions of React, and another is on GitHub, using package managers. In this tutorial, I use the “lite” version of the latter. I will walk through how to build the app, using all the goodies: npm, webpack, Babel for JSX, and ES6!


To follow along, you'll need:
  • basic understanding of React
  • working knowledge of the npm package manager to download, install, and manage dependencies
  • working knowledge of the webpack module builder, to bundle JavaScript and other assets for the browser (it works similar to grunt or gulp)
  • Node.js and npm installed on your machine
This tutorial doesn’t cover how to get started with React. However, you can learn more from many other excellent Envato Tuts+ tutorials.
You are going to build a simple web app using PubNub now. PubNub is a Data Stream Network (DSN) that provides a global infrastructure which allows you to build and scale real-time apps and IoT devices easily. Here, you will create shareable “stickie notes”. This is the app’s user-flow:
  1. A user logs in.
  2. As soon as the user enters a name, the app retrieves the last 50 notes, if any.
  3. The user types something on the stickie pad, and hits the return key to submit.
  4. The new stickie note appears along with the other notes on your browser, as well as every other browser of all users who are currently online.
Now, let’s get started!
In your app’s directory, run npm init to set up your package.json file, and then install these modules.
Install webpack module builder, which compiles, concatenates, minifies, and compresses static assets for the front-end:
$ npm install webpack --save-dev
Install webpack web server to run a local server:
$ npm install webpack-dev-server --save-dev
Install React, React DOM, and CSS animation add-ons: 
$ npm install react react-dom react-addons-css-transition-group --save
Install Babel to use JSX and ES6. We’re going to write with ES6 (ES 2015), which is next-generation JavaScript, with the help of Babel, a compiler: 
$ sudo npm install babel-loader babel-core babel-preset-es2015 babel-preset-react --save
Install PubNub for real-time communication: 
$ npm install pubnub --save
Create your app structure similar to this:
And configure webpack.config.js:
See the entire config file on this GitHub repo.
Basically, you are setting an entry file (top-level file) and the output destination where all your js (and .jsx) files will be built into a single file, after you run the webpack command. Also, by setting watch: true, you ensure that webpack will watch your file changes and rebuild your output file automatically.
Include the script bundle.js in your index.html file:
Also, notice the element with an id=”container” in the body. This is where your React app will be inserted.
You can run your dev server with the command, 
$ ./node_modules/.bin/webpack-dev-server
Or you can set it up in your package.json by adding this line: 
So that you can run the server with the npm start command instead.
In your browser, go to http://localhost:8080/webpack-dev-server/, and you should see your application (a blank HTML page thus far) running there.
Open up a new app.jsx file under the app directory, as you configured for an entry point in your webpack.config.js. As you can see from the file extension, we are going to use the JSX JavaScript syntax extension.
First, import the modules and files that are required for app.jsx
The import statement, newly introduced in ES6, is used to import functions, objects or primitives that have been exported from an external module or script.
Then define a class, CollabStickies, which extends the React.Component class, using this ES6 class declaration. This is equivalent to the React.createClassmethod with ES5:
    );
  }
}
In the constructor function, you are setting the initial state of this mutable data, the stickieList array. We will update the array each time we get a new stickie note, using this.setState().
In the render function, use JSX to define HTML template-like virtual DOM elements. In this case, the custom components StickieWritable andStickieList are included. You can pass the mutable props and states to the components to use. We are going to define them later.
When you build the app, Babel will transpile all this ES6 and JSX syntax into ES5 that browsers can render just fine.
With ReactDOM.render(), which comes with the react-dom package, render theCollabStickies component on the DOM node in your HTML.
Here, you notice the username and color props. This data is used for theCollabStickies component and is passed to its child components.
The values should be obtained from the user login; however, to simplify the app for this exercise, let’s just use a simple window.prompt() to get a username, and then give a random color of stickie notes when the app is loaded. 
The localhost Server asking for your name
Although I am using the browser-native prompt dialog here, in reality, I recommend you create another UI component with login functions, or use the third-party dialog box component. There are many reusable components you can find, such as Elemental UI’s Modal, and Material UI’s Dialog.
Now, you are going to use PubNub to make the app collaborative.
PubNub is a globally distributed data stream network that allows you to build real-time applications easily. Its core feature, pub/sub, sends and receives data between multiple users simultaneously.
In this app, anybody who “logged in” can post messages on stickie notes and share them with other users.
How PubNub Works
To use PubNub in your app, make sure that the pubnub module has been installed and imported in the top of your file.
First, you need to initialize it to create an instance of the Pubnub object. You need your API keys during the instantiation, so please sign up to PubNub to get your own keys.
Here, you are assigning the username obtained from the “login” process as auuid, unique identifier. (In this exercise, we take any string entered by a user as an uuid, but in reality, you need a real login system so that each uuid is actually unique, with no duplications!)
Also, notice I am using the ES6 const declaration, instead of var for these global constant values. In ES6 a const acts as a read-only variable and represents a constant reference to a value. In the later example, you will also see the newly introduced let, which is a block scope local variable.
To create the sharable notes app, you are going to use PubNub's publish()method to send your note to everybody, while subscribe() lets other users receive all the notes. The subscribe() method is called automatically every time somebody publishes a new note.
In your React app, let’s call the subscribe() within componentWillMount(), which is invoked immediately before the initial rendering occurs in the app lifecycle.
The subscribe method is asynchronous, and when each operation is successfully completed, the message callback is called. At the callback, let’s update the stickie note list by setting the state of the stickieList array, which was defined in the constructor at the beginning.
In React, modifying your data with setState automatically updates the view.
We are creating the view (a UI component) later.
In the subscribe callbacks, you probably have noticed the funny-looking syntax with arrows, =>. This is called arrow functions, which has a shorter syntax than the ES5 function expressions. Also, this expression lexically binds thethis value. Again, with Babel, we can leverage all the ES6 awesomeness!
Also, we are using the optional connect callback to the subscribe method to retrieve “history”. This will fetch past data when the connection to PubNub is established for the first time.
The history() is a part of PubNub’s Storage and Playback feature, and in this case, it fetches the last 50 messages from PubNub. At the success callback, update the view by setting the state of the stickieList array here too.
Let’s create a class, StickieWritable. It is a stickie note component that takes a user input.
It renders like this:

Comments

You may also want to read these ⤵️

Referee kills player in a football match

A referee is facing murder charges after football players allegedly forced him to

Do not watch this while driving

Kids are lovely and fun to watch most times. I know most of you did this and so many other funny stuffs as a kid. Feel free to share yours... Do not watch this while driving

Over 40 Million Accounts Found Guilty

Microsoft has uncovered 44 million user accounts using usernames and passwords that have been leaked through security breaches.

RAW TALENT ep1 (freestyle by Gdlpeid)

Just watch! Freestyle by ''Gdlpeeid''. A rapper with a difference.  Pure raw talent.

These 10 Powerful Words And Phrases Defined The Decade

Honestly, it has been a wonderful decade to remember.  A lot has happened and a lot has been spoken also. But our focus is on the words and phrases spoken.  Below are words and phrases spoken between 2010 - 2019 that defined the decade.....

By February 2020 - WhatsApp Will Stop Working on These Phones

Every now and then, WhatsApp does fish out a list of old phones for which support is discontinued and if you have an old phone lying around as a backup, you might want to read on.

Apple Has Released iOS 13.2.2 And Fixes Major Issue

All thanks to Apple,  the tech  giant just released iOS 13.2.2, which addresses the issue of background apps being killed prematurely, along with a handful of other annoyances.

This Magnetic thread Can Be Used To Clear Blood Clot in The Brain

Link from mashable.com  Researchers at MIT developed a thread that can be steered magnetically to glide through the brain's blood vessels and

This gigantic monster device turns wave energy into electricity

This 826-ton buoy was developed by OceanEnergy to turn wave energy into electricity. IEEE Spectrum reported that "OE Buoy" was towed from Oregon to Hawaii, where it will undergo a series of tests that will prove whether it can withstand the battering waves while generating electricity. Click the link below to watch the video..

Lionel Messi Barcelona exit date revealed

The Barcelona Legend has decided on when he wants to quit the club and even has a successor in his mind already.