React JS – Infinite Sub Menu

I’m going to mention right off the bat this tutorial doesn’t end with you having a ready to use menu. BUT.. it shows you a simple concept you can use to create the elements necessary for the old school infinite sub menus.

Infinite Sub Menus Were All the Rage

It’s been quite some time since I’ve seen infinite menus used. Maybe it’s because people are becoming more mobile conscious in their design decisions. The only way I could see infinite sub menus be mobile friendly is if the sub menu completely replaced the previous one.

It’ll probably seem ridiculously obvious once you see the solution but it may come in handy in the future. Here are two React components; List and ListItem, that can be used to accomplish infinite sub menus.

The Components

 

 

Notice the second import statement. My components are in a directory structure as follows:
-components
–List
—index.js
—List.js
–ListItem
—index.js
—ListItem.js

Because I’m a sucker for modular organization even with simple examples.

Now for the ListItem component:

 

 

Basically the solution comes down to the line
{ items && <List items={items} />}.

We’ve created sort of a circular dependency where a List, has ListItems, which can potentially contain another list. If you’re not sure what’s happening, React is looking at the items variable, if it does not equal undefined, it will continue to the other half of the AND (&&) comparison displaying a new list.

This is also true for vanilla JavaScript. If the first half of an AND comparison fails it will not bother with the rest.

Finally, I’ll give you a quick example object passed to the List component.

That’s all there is to it. Let me know if you have any issues with the following code.

Flashing ESP-01 with new Firmware

Flashing the ESP-01

I used a breadboard to wire up the programmer just because I thought it was easier. You could wire these chips directly to each other, just don’t solder them. My components came with the pins in different spots than what I’ve seen in tutorials so I’ve used a schematic to show the connections.

NodeMCU-Firmware-Flash-Schematic

Make sure the jumper on the FTDI programmer is set to 3.3v!

It may be important to note at my ESP-01 didn’t have a pin labeled CH_PD. Instead it was EN, so use that if your module is the same as mine.

Now that we have the connections set up, we need firmware to update the module. Luckily there’s a slick cloud service to create your own build. I selected the following modules to be included just as a test: file, gpio, http, mdns, net, node, tmr, uart, wifi. As far as I know this module will require the 1.5.4 branch to have enough space for modules and sketches. You’ll be given two builds of the firmware, an integer one and float one. I don’t know all the differences but if you’re planning on using floating point numbers you’ll want to install the float version.

Once you have your firmware you’ll need an application or script to flash the ESP-01. There are a few ways to do this, I prefer the NodeMCU-flasher application. It’s simple to use and hasn’t let me down yet. In the future I’ll try some cross-platform approaches because I prefer to be on Linux,

So, if everything is wired up correctly you can go ahead and plug it in. If you have the NodeMCU flasher started , in the ‘Operation’ tab you’ll notice it’s likely selected the port you’re plugged into.

In the ‘Config’ tab, you’ll want to add your firmware that you had customized from the cloud service.  To open it, click on the gear looking symbol and find your firmware. Make sure your Offset is set to 0x00000 to install at the base of the module.

In the ‘Advanced’ tab the only thing I had to change was the Baud Rate. It defaulted to 203400 but the firmware should be flashed at 115200.

NodeMCU-Advanced-Firmware_Flash

That’s it! Back on the Operation tab you can hit Flash. You’ll notice it’ll find the 2 MAC’s typically one character off from each other.

Once the flashing is complete you’ll see a green circle with a check mark if it completed successfully.

NodeMCU-Firmware-Flash-Complete

To confirm this, connect to the device through a serial terminal, I use PuTTY. Same COM number as you’ve flashed, and the baud rate will be 115200.

NodeMCU-Firmware-Flash-PuTTY

Disconnect the GPIO_0 pin from GND (ground). Take a jumper cable and connect it to RST on the ESP-01. Carefully tap the RST wire to GND to reset the module. You should see something like the following:

NodeMCU-Firmware-Flash-Confirmation

Don’t worry about the lua error. It’s common to see that when you haven’t uploaded any code to run on startup.

Troubleshooting the NodeMCU Firmware Flash

While getting to know this little module I had a hell of a time getting things to work. Here are a few problems I had:

Write flash timeout

This was pretty cryptic because I had all the settings correct but it just wouldn’t flash. The problem was there just wasn’t enough power to flash the module from my USB 2.0 port. Once connected to a USB 3.0 port it worked fine.

After hitting the flash button, it just spins/hangs/does nothing.

This could be because the module didn’t receive power while connected correctly. Double check the connections, take a jumper cable, connect it to the RST pin and tap it to ground. This resets the module, try flashing again and it should work.

React License Flip-Flop

Has anyone else been following the React license flip-flop? They had me worried for a bit. I’ve dedicated some time and effort to engulf myself in this environment and it was nearly stripped away with a blog post.

Facebook had changed React’s license to a BSD+Patents license.  The Apache Software Foundation did not like the grant in the license because it was “imbalanced towards the licensor”.[1] This sounds a little sneaky, but according to a post released by Facebook it was to protect themselves from “fighting frivolous lawsuits”.[2] This I could understand.

Facebook and a multi-billion dollar company. Which is likely a huge target for patent trolls and others looking to make a “quick”, not really though, buck. The BSD+Patents license was not well accepted like I mentioned before.

The Apache Software Foundation had listed the license under Category-X. Licenses that should not be included with Apache products. This is a pretty big deal, because to me, it sounds like you would not be able to license your software under the Apache License v2.0 for example if it included React source. Usual disclaimer, I’m not a lawyer, yada, yada, yada… lobster bisque.

I’m sure there are those who don’t care about the change. But if you’re developing software for millions of people, it’s something that needs to be taken into consideration. The biggest thing that stood out to me was a post by Matt Mullenweg.[3] He’s one of the founding developers of WordPress. If you can’t tell, you’re on a WordPress site right now! I know it’s the default theme…

In Matt’s post he announced one of their largest open source projects would be rewritten from React due to this license change. That’s crazy, scary, and frustrating all at once.

For those of you who don’t know, Gutenberg will be a new editor developed by WordPress, check it out!

Rewriting an application due to a license change just sucks. The scary part is that this could happen at any point to other libraries. Makes you kind of feel like Tweek from South Park.

But recently Facebook had decided to change their licensing again. And I’m sure glad they did. A post about a week ago from Facebook revealed they would relicense some of their open source projects under the MIT license.[4]

I’m very happy for the change, though in the post Adam did not sound as delighted. I hope they can leave their projects under the MIT license because I believe it will be adopted much faster this way. As for the patent trolls, they need larger penalties for losing, IMO…

[1] –WHICH LICENSES MAY NOT BE INCLUDED WITHIN APACHE PRODUCTS? –  https://www.apache.org/legal/resolved.html#category-x

[2] – Explaining React’s License – https://code.facebook.com/posts/112130496157735/explaining-react-s-license/

[3] – On React and WordPresshttps://ma.tt/2017/09/on-react-and-wordpress/

[4] – Relicensing React, Jest, Flow, and Immutable.jshttps://code.facebook.com/posts/300798627056246/relicensing-react-jest-flow-and-immutable-js/

API Versioning – Using Date Released

While browsing Hacker News one day, my favorite news site, I came across Stripes versioning blog post. This was not the first time I had come across the idea of using dates to version your APIs, but this time I decided to give it a try.

Some Background

I’ve commonly seen others suggest simply putting version numbers in the URL to segregate major changes. This can work, but how often are major changes made to your API?

In my experience changes are typically updates to some of the returned data, or additional parameters required for precision. These are small changes but not always backward compatible.

If this happens somewhat often, you’ll be supporting many different versions simultaneously. Not only that, you’ll need to duplicate API endpoints that haven’t changed just to be part of these new versions.

Instead of duplicating the entire API to make some small changes, there is a way of just adding changes to the single endpoint. The following is mainly a proof of concept, but with some modifications it could definitely be a solution.

Using Dates to Access API Versions

So finally, I’ll get right to it. By utilizing the flexibility of the HTTP header we can send the date which our client is able to support. This is done by adding an API-Header with a value of let’s say ‘2017-02-10’.

By sending this date in the header, you’re saying that your client is compatible with all revisions prior to and including this date. If your client will always be up to date, simply use today’s date as the value.

Routing to Specific Versions of APIs

So now that you understand the client side, I’ll explain a little how the API routes the request. Express allows you to create multiple routers with different prefixes. The goal is to generate new routes based on timestamps of when the changes were done.

There is middleware in the express server that extracts the API-Version header value and converts it to a timestamp. The middleware then uses this timestamp to reroute the request to the version compatible with the timestamp. The following image will hopefully help explain.

Example of API Date Versioning Routing

You may be thinking, what happens when you release versions that don’t include changes to each endpoint. Well, in the same middleware the routing take place, it actually loops through the endpoints to find a matching url, such as ‘fn1’. The routers are obviously sorted in ascending order to match the latest one with the requested API version. But this way, if a version was not updated in the latest release that was requested, the latest updated version will be used.

It may be easier for some just to look at the code, so I’ve put together a quick project and threw it on GitHub. Check out my date-version-api project on GitHub. Let me know what you think.

API Blueprint – Mock Server

Mock Servers from API Specifications

Last week I mentioned an API specification called API Blueprint. Turns out not only does this allow us to document our API, but also use it.

That’s right, create a functioning mock server from that same API Blueprint used to document your API. I did mention this a bit in my previous post but I thought I’d put together a quick example.

Install Drakov

sudo npm install -g drakov

I just grabbed the Polls API example from the blueprint examples.

I renamed the file to have a .apib extension. Run drakov like the following:

drakov -f PollsAPI.apib

Now you can access a mock server to test your front end code with! See the picture below for example.

api-mock-server-drakov

Drakov Tips

If you’re running the mock server on a different host and from a browser, be sure to enable  OPTIONS. To do this use the –autoOptions argument. This is because when the browser is accessing another host it will send a pre-flight OPTIONS request to see if the intended request is allowed. This bit me when creating my first NodeJS Express applications, I will always remember, vividly.

Use Notepad++ to find and replace tabs in your API Blueprint. Drakov can’t parse blueprints with tabs 🙁 .

 

API Specification – API Blueprint

What’s an API Blueprint?

An API Blueprint is actually a specification used to describe an API. Its source is a markdown file using plain text formatting. The specification enables a software developer/architect/whatever to use their documents with other applications/tools that adhere to the same specification.

What’s so special about using a specification?

You actually create a document based on a specification. This way, both humans and software can read it. Since it follows a common format/structure, software can parse these documents and use the contents. The contents can be used for some things such as documentation and mock servers.

Why bother making an API Blueprint?

It may seem like it’s just a lot of additional work, but it can save development time drastically. Real example, I had introduced this blueprint idea at work and decided to go ahead and build it. I had not even started programming this API yet but I created the blueprint for what my fellow coworker and I agreed on should be included in the API.

From this, I used a NodeJS tool called Drakov to create a mock server. While I was busy working on a separate application. My coworker was able to program his application using the mock server just like he would a server in production. The responses can be somewhat limited, but can easily be modified.

Not only was this great because he didn’t need to wait for me to program the API for his testing. But we found changes that needed to be made to the API for his application to function as desired. We were able to make a solid API design without rewriting any parts of the API while the client application was being built.

Documentation was mentioned…

Yes, the documentation aspect is wonderful. I think source documentation is underrated, but API documentation is a necessity. I used a tool called aglio to generate documentation for the API. Using the same markdown file (API Blueprint) created for the mock server, aglio generates its documentation. Check this example out from aglio below.

API Blueprint aglio example

This is the cyborg theme which looks pretty cool IMO. In the generating of the documentation, no html is needed. You can however use HTML to manipulate the icons and some styles.

Another thing worth mentioning. When using aglio to generate the documentation, it will also generate the response schema. This is a description of the object being returned. You can also use this schema to validate your json responses, also in unit testing! I’ll get to that another time…

I hope you found this post informative! If you have any tools you’d like to share please leave a comment. Maybe even a new parser or theme for API documentation, please share.

I’ve FInished Taking the Online Course – Intro to ReactJS

Full disclosure, I wrote my previous blog post about the Intro to ReactJS course a week or so after I started it.

For those who didn’t know, I started an edX course not too long ago. I chose ReactJS because I was already familiar with it but was hoping to find a few gems.

Intro to ReactJS is Basic, But Good!

Unfortunately because it was an introduction course, there wasn’t much to be learned from the content. However, the discussion boards were very good.

At the end of each module you’re asked to complete a lab assignment. This typically consisted of a small application showcasing recently learned aspects of ReactJS.

A graded mark was given out to those who reviewed and critiqued others’ work. This was a great way to see different ways a problem could be tackled. Having fellow programmers review my work was great too. I’m not perfect and the reviews gave me a better idea of how I should be designing ReactJS applications.

I was going to blow away my peers…

Since I was familiar with the library, I may have been a tad over-confident. The first module I designed my components in a way to be reused in multiple future situations.

You may think this is good. That’s how components are meant to be written(not really true). If the components needed to be reused later there would be very little to no refactoring.

YAGNI

The thing is, I knew this would be the last time I would open the source. There was never going to be any more updates to the application. This is where I should have thought of YAGNI (You Aren’t Gonna Need It).

Don’t get me wrong, thinking ahead and preparing for change is important. But what I really should have been considering, is the possibility of needing the functionality I was introducing. Which was zero.

It was a good learning experience and I’m glad a fellow peer had called me on it.

Course Content

The content I thought was well put together. This was my first edX course and it won’t be my last. I’ve already enrolled in another one.

The content includes both written and video media of the same content. This allows you to consume it how you like.

Personally I stuck with the text just because it was slightly faster.

The assessments (tests) were not bad. There were definitely some question/answers I thought could be improved. For the most part it was well done though.

The course was listed as an intermediate course as it should be. If you’re not familiar with JavaScript and HTML I don’t think you’ll do well. This course stays strictly on the topic ReactJS which was really nice. No fluff, just focused content.

I hope this helps anyone considering looking into edX’s courses, maybe I’ll see you on the discussion boards.

Have experience with other courses? Please leave a comment and let me know about it! Also if there are some resources you’d like to share, that would be great too.

I’m Taking an Online Course – Intro to ReactJS

I was browsing some of my favorite info hot spots when I came across a list of resources. They were free learning resources containing mainly books and online courses.

This sparked a memory of me taking some courses at Udacity. I had first come across it a few years back and took the Intro to Computer Science course. This course was (is?) built around using Python to create a web crawler.

Man reading a book beside a laptop

Free Learning for All

I thought the Udacity course was very well done. Especially being a free online course. Assignments were marked automatically. YouTube videos were interactive and allowed you to answer multiple choice questions.

It was a great experience.

I’m always looking for new resources to learn from. Every day I venture to PacktPub’s free learning page to see what free book I can get my hands on.

I’ll be honest, the majority of them will go unopened. But whenever I come across a topic I’d like to dig into I’ve got a heap of books that may help.

Some more great resources are Hacker Bookshelf and Leanpub.

Leanpub is a hidden gem I had come across nearly a year ago. Not everything is free. But I have read some good free content from this site.

If I ever create a book, I’ll likely use this platform to publish it.

Back to the Online Course

Trailed off a little there, but hopefully some of those links will be useful to someone.

So I decided to try out an online course on ReactJS.

Why ReactJS?

Well, I do have experience in ReactJS, but I want more. It seems whenever I read tutorials, books, watch conferences, etc. I learn something new about ReactJS.

There’s just so much to learn in React. And not every resource will cover things necessary for a production ready application.

The course is created by Microsoft but hosted on edX. I’m not paying for the certificate because I don’t feel I have the need for it. But I will audit the course and let others know how it was.

So, my journey through Introduction to ReactJS starts now.

Beautiful Code Formatting by Linting with ESLint

What is “Linting”?

Linting is a process of checking source code for suspicious or non-portable constructs. Or at least one definition… [1]

There are many extensions and programs to provide linting functionality for Javascript. Some of these are; JSHint, JSLint, and the one I have been using lately, ESLint.

Some may say that linting isn’t worth the effort. [2] I personally, disagree…

Linting provides a way to enforce code style standards. It can be hard to enforce code style standards on a team sometimes. People disagree with how things should be styled, they may have habits for their own style methods already, some even forget the standards exist.

Another great benefit is keeping your source lean. In ESLint at least, you can configure it to flag variables that are unused. It sounds obvious that you would just remove those variables. But in large files of source, it may be difficult to see the variable is no longer used after an update.

Tech Company Base Rules

Airbnb has a detailed style guide. I like the description, “A mostly reasonable approach to JavaScript“. [3] Probably not a complete solution for all, but it’s a good place to start. In addition to these rules, you can add your own or even override them.

My favorite part about their documentation is where they explain why they have implemented specific rules.

You’ll likely need to install a few modules if you’re using Node.JS but these rules will get you started. [4] I use the ESLint extension published by Dirk Baeumer and have had no complaints. [5]

Finally, enforcing some new JavaScript conventions. Using keywords such as const and let instead of var. This allows the programmer to better describe the variable and define more specific scope. [6]

ESLint warning for using the 'var' keyword.

[1] – What is “Linting”? – https://stackoverflow.com/questions/8503559/what-is-linting

[2] – After 3 Months Of JavaScript Linting, It’s Pretty Much All Pain And No Gain – https://www.bennadel.com/blog/3312-after-3-months-of-javascript-linting-it-s-pretty-much-all-pain-and-no-gain.htm

[3] – Javascript Style Guide – https://github.com/airbnb/javascript

[4] – eslint-config-airbnb-base – https://www.npmjs.com/package/eslint-config-airbnb-base

[5] – ESLint – Visual Studio Marketplace – https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint

[6] – What’s the difference between using “let” and “var” to declare a variable? – https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable

Modular Node.JS Application Programming

Modular Node.JS application programming has a number of benefits. You can isolate smaller portions of the application for packaging and testing. You can create small specialized packages to use with different hardware or peripherals.

One example I’ve used this approach with is microservices. Spinning up an unknown (to the application) amount of express servers.

In the following example I will show you how to create a simple helper module to import all modules within a specified folder. These modules can basically be anything you want as long as they’re contained in their own folders. It will help if all Node.JS modules contain a common function to initialize them.

The image below is the file structure I use for modular Node.JS applications.

Modular Node.JS File Structure

Let’s See the Source for Our Modular Node.JS App!

The following code block is libraryLoader.js:

So let’s quickly pick this apart. The function we will be calling from the main script of the application starts on line 23. I’ve separated the getLibraryDirectories defined on line 13 just to keep things clean.

In our main function, line 25, is simply using Node.JS’ path module to join a file path’s starting point, path to the directory, the operating systems separating character, then the directory itself.

Next, line 26, we use this full path to obtain the names of each directory in the target folder, they are stored in an array.

Line 28 is where the magic happens. For each item in the previously mentioned array of directory names, we import that folder and pass in an object to store it’s structure. This works because if you look at the file structure I provided earlier, modules in the lib folder have an index.js file. When importing, Node.JS will try and reference an index.js file in that directory if a file is not given.

Once the loop is complete, the filled libraries object is returned to whatever had called it.

I’ll now show you a small example of one of these modules in the lib folder to show how the libraries are added to the object.

The following code block is all the source located in index,js, the file I mentioned earlier that is invoked when a directory is imported.

This is extremely simple and only created for example purposes.

The passed in libraries object during the require can be seen on line 7. Node.JS will send a reference to that object which will include a reference to functions located in the app.js. In this case init(). According to Stack Overflow this is called square bracket notation.

A matching function can be found in Module1 and you’ll see why that is important shortly.

The following code block is app.js of the root of the application. This is where the libraryLoader helper will be called.

The usage is actually quite simple.

As you can see on line 9 is where we load all the libraries or modules and store them in a single object. This object contains keys which match the directory names located in the lib folder.

The parameters are:
__dirname – The current directory to start the path
‘.’ – A single dot to tell the function the directory is within the current location
‘lib’ – The directory name we’re looking for is lib, so each module will have to be contained in a folder within lib

Line 10 is just a simple example of how to call functions in all loaded modules. In most cases I will have an init function in all modules to set up loggers and configurations.

I’ll upload the source to Github shortly. Please let me know if you have any questions or comments!

Edit: I’ve finally uploaded the source to GitHub!