Friday, May 10, 2019

I had a two-day workshop with Eirik Vullum at the Norwegian Developers Conference on React.js.

I learned in this training that to preview .md markdown in Visual Studio Code that one should right-click upon its file in the Explorer and pick "Open Preview" from the options. As you might imagine, I also learned some about JavaScript. JavaScript is more declarative than imperative, etc. A .reduce example that takes in state and an action and alters state based on the action is a "naive" (Eirik's term) example of Redux state management. Eirik was quick to assert that the React API is pretty light and most of the problems that come up are really just JavaScript problems. The talk on JavaScript included a bit on the this keyword and when you have a method at an object the object will be the scope of this for the method. Bearing that in mind, you may not just assign the method to a variable and then call the variable as a function and expect the same behavior. If you want that kind of behavior you have to follow what is on the right side of the assignment with .bind and hand to .bind the variable name for the greater object the method hangs off of. The variable made in the assignment may be thought of as a bound function. .bind may also be used in a "partial application" wherein the first variable is the this and the variables after that fill in the various variables for the function kind of like as is the case in .call only you are not calling the function just then. When you call the partial application you may either hand in zero variables or, alternatively, any variables you do hand in will be sequentially after the ones already specified by the .bind at the function signature. Just about everything that is new in JavaScript compiles down to a less elegant way of doing things in old ECMAScript 5. One of the few examples of something that breaks this mold is proxies. Proxies allow you to put a middleman (a proxy) between a JavaScript keyword such as function and the use of function (per our example) to hack in your own behavior. This is scary stuff that is really of third party tools and should not be used in production code too often at all. In an interesting use of deconstruction one may assign an array of three things to an array for two variables and just have a double comma between the two variables to only assign the first and last of the array items to the variables. One of the criticisms Eirik made of certainly AngularJS and to some extent the modern Angular is that the templates have their own proprietary markup that makes for a superset of HTML wherein some "crippled" JavaScript may be spliced in here and there inside quotes. I know what he meant by crippled too. It was suggested that this is a separation of technologies instead of a true separation of concerns. There are some things you cannot do inside of an *ngFor and there is a lot of Angular-specific stuff to learn to get *ngFor to behave refined/robust. Perhaps a better way to go is to just have JavaScript return some JSX with HTML markup (and just HTML) inside of the JavaScript. This is cornerstone to React. We talked about high order components in React as modeled on high order functions in JavaScript. High order functions take in one or more functions and return a function. The function you get back may then get called to undertake the same functionality as what was handed in and also some extra goodness that got bolted on by the high order function along the way. For example, if we wanted to log something to the console every time we called a few of our functions, we could pass each of our functions through a high order function that jammed in the logging and then just use the outputs from the high order functions in lieu of our regular functions downstream in code. The way third party code extends your components in React is with high order components. You will hand in your component and get back a new component which is your component and then some. This is, yes, an example of the decorator pattern. The training had a pretty good description of callbacks versus promises in JavaScript. When using a callback, the callback is handed into a function that will use it when done with an asynchronous operation and the function itself will not return anything. It will just call the callback when the time comes. By convention, the callback will take two arguments, the first being a representation of an error in the event of an error and the second being the data to be returned upon success. These are kind of painful to use when chaining asynchronous operations and thus, enter the promise.

function fetchMessages() {
   const myPromise = new Promise((resolve, reject) => {
      var time = new Date();
      var year = time.getFullYear();
      if (year > 1957) {
         var messages = [
            "We have spacefaring.",
            "We have sports cars.",
            "We have hula hoops."
         ];
         resolve(messages);
      } else {
         var error = "We've got nothing.";
         throw(error);
      }
   });
   return myPromise;
}

 
 

Use the promise like so:

fetchMessages().then((messages) => {
   messages.forEach((message) => {
      alert(message);
   });
}).catch((error) => {
   alert(error);
});

 
 

Note now that variablewise the success use case is first and the error use case second. Instead of doing the .catch we could have had a second function as a variable in our .then for the reject variable in the promise to call out to, I know. I wanted to show off the .catch. React came to be at Facebook and Facebook uses it at Facebook itself to this day. This is an important distinction from Angular with which Google does not seem to be architecting any of its own applications. It is reasonable to say that of the two rivals that React is better vetted as the issues to be faced are faced by the most used web site in the world daily. Angular, as a Google offering, is rather comically bad for SEO, but there are ways to make React agreeable. Template strings use backticks instead of apostrophes. Behold:

var time = new Date();
var year = time.getFullYear();
var concatenation = `It is the year ${year}!`;
alert(concatenation);

 
 

The facebook/create-react-app lets you use TypeScript and this is considered the best starting place for making a new React application. That said, the above is a template literal in modern JavaScript and not merely TypeScript creeping in. One of the React components from Eirik's exercises was:

const CheckboxWithLabel = class extends React.Component {
   constructor(props) {
      super(props);
   
      this.state = {
         isChecked: false
      };
   }
   
   onChange() {
      this.setState({
         isChecked: !this.state.isChecked
      });
   }
   
   render() {
      return (
         <label className="CheckboxWithLabel">
            <input
               type="checkbox"
               checked={this.state.isChecked}
               onChange={this.onChange.bind(this)}
               />
            {this.state.isChecked ? this.props.labelOn : this.props.labelOff}
         </label>
      );
   }
};

 
 

Things to notice above are the JSX, the template literalesque injection into the JSX, and the props variable at the constructor which has to be handed into to super to end up in the parent constructor for React.Component or else things break. "Fullstack React: The Complete Guide to Reactjs and Friends" was recommended as a good book to read and I ordered myself a copy based exclusively on the fun vaporwave cover art. A new feature is hooks which allows you to use "functional components" for a complete replacement even of components. You can tie into the state associated with a component and the lifecycle stuff without actually writing a class. All hooks follow a useSomething naming pattern like so:

import React, { useState } from 'react';

 
 

https://graphql.org/ has some details on GraphQL. GraphQL is used heavily in this space, heavier than anywhere else. Jest is most commonly used for testing and supports snapshot testing giving you screengrabs of test results, etc. You may play with React in a shell environment with react-blessed. The let keyword is another example of something that exists in modern JavaScript which I saw in TypeScript first. The JavaScript version has the same better blockscoping with let and the const keyword also does the blockscope thing. const cannot be reassigned. Browsers should blow up at a const reassignment. There is a concept of short-circuiting in JavaScript which behaves kind of of like a ternary operation.

const result = false && somethingMore;

 
 

We won't get to right side of the double ampersand if the left side is false and should it be true then the right side of the double ampersand is really all that matters, isn't it? Get how it is like a ternary operation? There are some assignments in React where the second half of one of these is some JSX, wrapped in parenthesis, shown or hidden upon a condition. npx is another package executor like npm and you may install the create-react-app with it with this command line command:

npx create-react-app your-application-name-here

 
 

Make a pooped-out build folder with TypeScript compiled to JavaScript and what not with this command at a create-react-app application:

npm run build

 
 

Just run the app the same way you'd run an Angular application:

npm start

 
 

The only way to have the async keyword at the top level scope is with a hack like this, and, yes, you have to have the leading async keyword to use async.

(async function() {
   doSomethingMore();
}());

 
 

This is a point of discussion amongst the TC39 (Technical Committee number 39) due to the pain point above, but it's best to keep in mind that JavaScript is broken and that you can never fix it. "You learn by being burned." is a direct quote from Eirik Vullum. sort-by is a package from npm which plays nicely with .sort. You hand into a .sort as a variable sort-by immediately followed by some variables in parenthesis to get a sort order with regards to whom should be first, second, and last in order of a sort. .reverse and .sort mutate their lists while .slice and .map do not. With .slice and .map you are making a new list instead. In something like an MVC pattern where you have models, views, and controllers, there are four comparable parts used by convention not necessity to keep a React app from turning into a big ball of mud. These are symbolized by the colors blue, red, green, and yellow and if you are doing things well you should have distinct colors on different sides of the various boundaries of a React app and not just a blob of brown. View is blue and this is React itself. Views send commands to control flows. State is red and state gets handed to views. State is managed by Redux. Redux Thunk is middleware symbolized by the green color and the term control flows. The control flows take commands from views and send events to state so to speak. They also crosstalk with services. Services are yellow and you might use Axios for services. Services talk to API endpoints. react-router is recommend for routing. Loop in new tools like this at the package.json file. I enjoyed myself at the Norwegian Developers Conference and there will be more blog posts to come of the various talks I saw. I don't know who the gentleman with the mohawk seen here manning the C. H. Robinson tradeshow booth was but he seemed pretty used to people walking up to him and talking a photo of his profile without explanation. I guess no explanation is needed, huh? This is probably the best conference I've yet been to and it certainly had the best catering. I didn't try the bacon covered donuts as they grossed me out at a glance, but I came to find afterwards that this is a Minnesota thing like putting peanut butter on top a hamburger (well, that's more Midwestern in the big picture) and just a normal part of my new environment not a nutty Norwegian trapping.

No comments:

Post a Comment