REACT & REDUX – tracing the steps…

THE NORMAL REACT STUFF

  1. Develop the code which: reads an input and writes to (local) state upon submit.
  2. the render() reads from (local) state and lists out the data.
  3. This will eventually be the PRESENTATION layer of our App.

THE REDUX STUFF

  1. Create a storewhich ties to a reducer
  2. Create a reducerwhich performs action based on the type
  3. Normally, we dispatch the (Add/Edit) function(s) using store(dot)dispatch
  4. Don’t dispatch the function(s)for now

THE REACT meets REDUX STUFF

  1. Presentation Component has all the details related to the UI/UX;
  2. mapStateToProps
    • helps MAPS the STATE to PROPS (when we replace STATE by PROPS)
    • This is for FETCHING Data from the Redux Store
    • put the properties here which you want to return and print on the screen
    • This is where you replace this.state.propertyName by this.props.propertyName
    • here we declare what pieces of state you want to have access to (we got access to message only)
  3. mapDispatchToProps
    • helps MAPS the DISPATCH to PROPS (when we replace STATE by PROPS)
    • here we declare which action creators you need to be able to dispatch (we got access to subitNewMessage only)
    • in React: upon a click event, we used to update the state like setState( messages: this.state.messages.concat(currentMessage) )
    • Now, to use Redux: We do props.submitNewMessage(currentMessage)
    • submitNewMessage didn’t exist before, this is defined inside the mapDispatchToProps function
  4. connect
    • used for bringing it all together
    • Container is used to connect state & dispatching with the

basic Code for react redux (as per listing above)

 

Redux – Immutability

Methods for enforcing the key principle of state immutability in Redux. Immutable state means that we never modify the state directly, instead we return a new copy of the state.


const immutableTypesDefaultState = { lastInput: '', messages: ['message1', 'message2', 'message3'] };
const immutableTypesReducer = (state = immutableTypesDefaultState, action) => {
switch (action.type) {
case 'ADD_BAD': { /* BAD !!! PUSH IS STATE MUTATION */
// this.setState({ messages : this.state.messages.push(action.input)});
//console.log('looking to push ['+action.input+'] into messages array');
var newArray = state.messages;
newArray.push(action.input);
return { lastInput: action.input, messages: newArray };
}
case 'ADD_GOOD_NORMAL': { /* GOOD !!! THIS IS NOT MUTATION */
//console.log('looking to add ['+action.input+'] via concat');
var anotherArray = state.messages;
anotherArray = anotherArray.concat(action.input);
return { lastInput: action.input, messages: anotherArray };
}
case 'ADD_GOOD_SPREAD': { /* GOOD !!! THIS IS NOT MUTATION using the SPREAD operator */
//console.log('looking to add ['+action.input+'] via spread');
var yetAnotherArray = [...state.messages, action.input];
return { lastInput: action.input, messages: yetAnotherArray };
}
case 'REMOVE_ITEM': { /* GOOD !!! THIS IS NOT MUTATION using the SPREAD operator */
//console.log("requesting to remove an object on index:",action.input);
var slimmedArray = state.messages.filter(val => val != state.messages[action.input])
return { lastInput: action.input, messages: slimmedArray };
}
case 'OBJECT_ASSIGN': { /* GOOD !!! THIS IS OBJECT ASSIGNMENT WITHOUT MUTATION */
//console.log("requesting to change an object while enforcing state immutability with:",action.input);
var changeObject = Object.assign({}, immutableTypesDefaultState, { lastInput:action.input} );
return { lastInput: action.input, messages: changeObject };
}
default: return state;
}
}

const ImmutableTypesStore = createStore(immutableTypesReducer);
console.log(ImmutableTypesStore.getState());

setTimeout(function () {
ImmutableTypesStore.dispatch({ type: 'ADD_BAD', input: 'sample input for push' });
console.log(ImmutableTypesStore.getState());
}, 2000);

setTimeout(function () {
ImmutableTypesStore.dispatch({ type: 'ADD_GOOD_NORMAL', input: 'sample input for Good via concat' });
console.log(ImmutableTypesStore.getState());
}, 4000);

setTimeout(function () {
ImmutableTypesStore.dispatch({ type: 'ADD_GOOD_SPREAD', input: 'sample input for Good via spread' });
console.log(ImmutableTypesStore.getState());
}, 6000);

setTimeout(function () {
ImmutableTypesStore.dispatch({ type: 'REMOVE_ITEM', input: 1 });
console.log(ImmutableTypesStore.getState());
}, 8000);

setTimeout(function () {
ImmutableTypesStore.dispatch({ type: 'OBJECT_ASSIGN', input: 'Object.assigned was used for this' });
console.log(ImmutableTypesStore.getState());
}, 10000);

Audit score on Google Lighthouse (PAK)

Optimizing website with zero budget: my journey

TL;DR

I optimized the beta version of my website to some really high scores on leading website performance auditing tools; I share my experience with these tools. Check the banner image or check the website at https://beta.akberiqbal.com.

What makes a great website?

For those who give more importance to visual design, it can be anything from a flashy design with high-resolution images and video to others who prefer a minimalist, simple design. For a more educated consumer, it would be a website which is tailored for its visitor, covered generally as usability or user experience, it is a detailed topic, put simply as the ‘ease with which a consumer can get the information they need’.

For millennials and mobile users, it would be speed. Users on mobile account for more than half of all visits to websites and for these users design needs to be responsive, size should be optimized for 3G connections and usability is a metric which becomes more important on a mobile’s real estate.

For some users and governments, accessibility would be a must-have and it helps ensure that the web is inclusive of all, given the numbers of this demographic. We have all heard that content is king, and with proper search engine optimization, it brings more visitors to a website.

For a web developer, what would be a great website?

There are many tools out there which try to answer this very question; It is primarily done by benchmarking and setting best practices. Among the many tools out there, I will only discuss a few which are closer to being at the top of this pile in my opinion and which I used to develop an optimized ‘beta’ version of my website.

To make things interesting, the budget for this website optimization exercise was $0. To this day, I only pay for the domain and hosting only. No other paid services at all. Following will be a brief introduction and experience over my journey with these tools.

Google Lighthouse: a very comprehensive tool, built for developers and part of the Google Chrome browser, it can audit any website for performance, best practices, accessibility, SEO and progressive web application (PWA). Auditing your website here will probably return a lot of pointers and suggestions at first, and they are really helpful in understanding how the web works and how we can get more performance out of our websites.

PWA was really interesting, it uses Service workers to empower web applications to deliver a user experience with the reliability and performance of locally hosted websites. This is a giant leap in the world of websites; a website which behaves like a mobile/desktop application by choosing whether it needs to download a website component from your web server or whether it can use it off the local cache. On Android phones, a pop-up asks whether you want to install it or not, in case you install it, you’ll see an icon on your mobile to give a complete mobile application experience.

Audit score on Google Lighthouse (USA)

Audit results on the right: Performance 84/100, Progressive web app 100/100, Accessibility 100/100, Best practices 100/100, search engine optimization 100/100

I was able to achieve a perfect score in for accessibility, best practices, SEO and progressive web application but performance was topped at 87 and 80 on two different machines which I had. If I had invested some cash in it, there are plenty of tools which could help get a performance score of 100.

Google PageSpeed: a tool which tests a website on desktop and mobile to return a real-world performance score. Be prepared for lots of pointers at first, which all help make the website lighter, faster, better. In case of my beta website, the only Achilles heel turned out to be two Google tools. The fact that Google tag manager and Google analytics have a short browser cache expiry of 15 minutes and 2 hours respectively meant that I was penalized and it prevented a score of 100. It was ironic especially because both of these tools were made by Google, who also owned this performance website. Again, there was no budget for optimization, so I didn’t go for a paid analytics tool which could have covered this particular metric.

Google PageSpeed Score

Audit results on the left: Desktop 98/100, Mobile 96/100

GTmetrix: very similar to the other two tools discussed above in many aspects like a timeline, loading times, size etc. GTmetrix helped by breaking down the individual components on the website and how optimizing these particular assets could help achieve a perfect score. Cache times for Google Tag Manager and Analytics took away some percentage points to leave me at 98% on the performance score. The details which were really interesting were the need to specify image dimensions and how minified Javascript files for analytics could help get a perfect score. This tool lets you download the result of your website as a pretty report which you can use to analyse and improve your website.

GTmetrix score

GTmetrix scores on the bottom

Web Page Test: I first saw it on the dialog box which opens up during the lighthouse audit run. It is a web-based tool, which lets you simulate your website views from a variety of pre-set locations and devices which help deliver a complete usability and performance score. Usage of cache and compression was the thing which was unique about it along with other metrics which were covered by the tools discussed above. Third party scripts and rest APIs did cost me some percentage points here. My website resources were cached by my CDN provider and the font file there was not compressed, which cost me some points. Again, with a working budget, this would have been solved.

WebPageTest performance test score

WebPageTest.org performance test score

Can any website be optimized to get these scores?

Short answer: No. Try your favourite website with these tools.

Long answer: You don’t necessarily need to. A website is created to serve its audience; to understand and fulfil their unique needs at the cost of limited time and resources. Analytics can help understand a website’s audience, their needs, locations, technology, behaviour and time spent. All of which is invaluable in tailoring the experience for that customer.

Some of the best practices outlined in these tools will take a lot of time for very little return. Some of these would not take all that long but might make the maintenance of the website very expensive in the long run. Hence, some metrics could be achieved by investing more capital and bearing more recurring costs. It is a careful balancing act which is unique to each website, its organizational setting, underlying technology, time and budget limitations.

And while all of this is done, a new set of standards and technological advancement may bring newer benchmarks and best practices. Network speeds at different times of the day resulted in different readings as well, but this is why I didn’t follow a single tool but followed multiple tools which could help test my website from different locations on different devices. It would be interesting to see where this website will rate in the next 3 months, 6 months, in a year!!

Lambda functions in TypeScript

lambda functions help remove ‘function’ and define functions inline – check the blue text on TypeScript website, which will give the output in red…

let a: number, b: number;
a = 23;
b = 14;
/* No parameters… simple return */
var simpleTen = () => { return 10; };
console.log(“Now calling simpleTen ” + simpleTen() );

var a, b;
a = 23;
b = 14;
/* No parameters… simple return */
var simpleTen = function () { return 10; };
console.log(“Now calling simpleTen ” + simpleTen());

/* One parameters… simple return */
let squareNumber: any = (a: number) => { squareNumber = a * a; return squareNumber;};
console.log(“Now calling squareNumber(“+a+”) is ” + squareNumber(a) );

/* One parameters… simple return */
var squareNumber = function (a) { squareNumber = a * a; return squareNumber; };
console.log(“Now calling squareNumber(” + a + “) is ” + squareNumber(a));

/* Two parameters… simple return */
let additionFunc = (n1: number, n2: number): number => {
/*let varTest = 10 + n1 + n2;
console.log(“(inside) additionFunc (with additional 10) is… ” + varTest); */
return (n1 + n2);
};
console.log(“Now calling additionFunc(“+a+”, “+b+”) is ” + additionFunc(a,b) );

/* Two parameters… simple return */
var additionFunc = function (n1, n2) {
/*let varTest = 10 + n1 + n2;
console.log(“(inside) additionFunc (with additional 10) is… ” + varTest); */
return (n1 + n2);
};
console.log(“Now calling additionFunc(” + a + “, ” + b + “) is ” + additionFunc(a, b));

var foo = () => ({ “name”: “test Name”, “age”: 21 });
console.log(“Now calling foo (which is a variable that contains the functiona and will hence return the function): ” + foo);
console.log(“Now calling foo() (which is a function call and will CALL the function to return an object)… [Name]:” + foo().name + ” & [age]: ” + foo().age);

var foo = function () { return ({ “name”: “test Name”, “age”: 21 }); };
console.log(“Now calling foo (which is a variable that contains the functiona and will hence return the function): ” + foo);
console.log(“Now calling foo() (which is a function call and will CALL the function to return an object)… [Name]:” + foo().name + ” & [age]: ” + foo().age);

Google: taking search to the next level

Arguably the most innovative company in technology and software has recently taken some big bold steps in the world of hardware. From the acquisition of HTC mobile unit to the launch of new hardware at this year’s event, Google seem to be taking on a lot more of hardware development to complement its search business.

Google’s original mission statement was “to organize the world’s information and make it universally accessible and useful”. It surely did that with the best search index (Google search), the most convenient & largest video library (YouTube), the ultimate map/guide (Google Maps) and the most popular internet browser (Chrome). One emerging big threat of Google is its ‘search’ business. What if we stop asking Google for stuff and go somewhere else with our search queries? What if we go to our preferred e-Commerce site for buying stuff or turn to Instagram to find/follow the people we like and share images or if we go to Twitter to get the latest updates? All of which will result in low volumes going to Google. To stay relevant and an important part of our lives, Google wants to proactively help us without us asking it directly, and to achieve this, it is using machine learning and AI.

Machine learning and Artificial intelligence (AI) are no longer buzz words, they are here and with advancements in processing capability, internet bandwidth and storage capacity, it is time that they can receive and process vast amounts of (audio and visual) inputs, not just text-based search queries. The real story of the Google event can best be observed through the enhancement of Google Pixel (flagship mobile device with Google Lens), Google Home (voice assistant) and introduction of the Clips, a camera which reveals Google’s focus on AI. These devices offer clue as to why Google got into the hardware business itself without relying on partners to showcase its software capabilities.

Google Pixel 2 with ‘Google Lens’: the flagship mobile device packed with the new ‘Oreo’ operating system and promises upgraded to the next 3 operating systems (instead of the two upgrade cycles), water-proofing, stereo-speakers, and a top performing camera which can argued to be the best amongst Android phones. Priced competitively to other high-end Android powered phones, it can be a serious contender to the iPhone. The camera features optical image stabilization, excellent low-light shots & to take a picture, just hold and squeeze the phone. It also features Google Lens, which mixes image-recognition and augmented-reality technology to let you point your phone camera at different objects to get more information about them, hence keeping the search business running and building upon it’s visual/image search project.

Google Home is all convenience, a device which sits silently in a corner (unless you want to blast music through its improved speakers), waiting for our instructions, queries & feedback. Although, our smartphones were well-equipped to do it for years, the level of accuracy has gone to a different level because the device needs to be on all the time. There is an argument that many companies listened and watched us secretly, which led to all software seeking our explicit approval before they could access our camera, contacts or microphone. With Google Home, we are explicitly allowing Google to be a family member and listen in. With hands-free convenience and low prices, its aim is to ensure that Google knows what’s going on in world – even though we might take searches elsewhere.

Google Clips is a stand-alone camera with intelligent software which decides which moments must be captured itself, no kidding, it doesn’t even need internet access to function – and it also gets smarter over time in light of our feedback over the pictures that it took, it is ground-braking in the sense that it doesn’t need an internet connection to work, the algorithm which decides what to capture, what to ignore is built into the tiny device itself. The wonderful thing with these devices will be the accuracy, something which builds upon study of billions of search queries from all over the world and specifically our history and our interactions with them. The technology powering these devices is building on learning from our smartphone interactions, years of study of what we ourselves posted on Facebook, Twitter, Instagram profiles, likes, shares etc.

Google is expanding on its search business with these devices and will surely hope that other hardware vendors get on the bandwagon to further accelerate the innovation in these key areas. Apart from Apple & Facebook, the only other company which can capture and process such an enormous amount of data is Google and with its latest offerings, we are allowing it unrestricted access like never before.

Angular 4: demo of observable vs. promise

Following code is meant to show the same REST API being called via a Promise and an observable. It was tested on:

  • OS: Win32, ia 32, windows 7
  • @angular/cli: 1.4.5
  • node: 6.11.3
  • npm: 3.10.10

 

app.module.ts

@NgModule({
declarations: [ AppComponent ],
imports: [ BrowserModule ],
providers: [ ApiService ],
bootstrap: [ AppComponent ]
})

 

app.component.ts

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
import { IPostType } from './IPosts.object';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
_postsArray: IPostType[];
_postsArrayPromise: IPostType[];

constructor(private apiService:ApiService) {}
ngOnInit():void {
this.getPostsUsingObservable();
this.getPostsUsingPromises();
}

getPostsUsingObservable(): void {
this.apiService.getPostsByObservable()
.subscribe(
resultArray => this._postsArray = resultArray,
error => console.log("Error :: " + error)
);
}

getPostsUsingPromises():void{
this.apiService.getPostsByPromise()
.then(articlesItems => this._postsArrayPromise = articlesItems);
}
}

 

IPosts.object.ts

export interface IPostType {
userId: number;
id: number;
title: string;
body: string;
}

 

api.service.ts

import {Injectable} from "@angular/core";
import {Http, Response} from "@angular/http";
import {Observable} from "rxjs/Observable";
import "rxjs/Rx";
import { IPostType } from './IPosts.object';
@Injectable()
export class ApiService {

private _postsURL = "https://jsonplaceholder.typicode.com/posts";

constructor(private http: Http) { }

getPosts(): Observable<IPostType[]> {
return this.http.get(this._postsURL)
.map((response: Response) => {
return <IPostType[]>response.json();
});
}

getPostsByPromise(): Promise<IPostType[]> {
return this.http.get(this._postsURL)
.toPromise()
.then((response: Response) => {
/*console.log("output during GET(promise)" + response.json()); */
return Promise.resolve(response.json());
})
}
}

iPhone Face ID: a giant leap in advertising

Facebook and Google make a big chunk of money through the ads, not just any ads, targeted Ads, which they can do accurately after analyzing our online behavior, which includes our likes, comments, posts, pictures, our browsing history, the time we spend on a particular type of content etc. They have complex algorithms which can accurately classify a person and then serve them content and Ads which appeal to them.

But however smart the algorithms get, they are unable to record the affect which a particular content might have on a person. Does the person feel happy? Sad? Angry?… the reliance of current algorithms is on the time spent on content, frequency of interactions with similar content, interest in the content by family, friends etc. There is a need for a more accurate metric on customer feedback.

Steps in #iPhoneX and #FaceID: which solves the missing piece of real-time, accurate customer feedback which is displayed through the emotions exhibited in the face… this must be invaluable data for the advertisers who can launch pilots which receive feedback with very high accuracy, can segment and categorize based on real life, undisputed data right from the customer.

Comparing a person’s face (without them knowing) at different times and against different set of content has a potential to give an incredibly accurate feeling-o-meter

We can put a tape on our iPhone X’s camera, sensors, dot projector to guard against it, but if you spent a cool grand on a new iPhone, why would you? Apple may not be the first one to introduce this technology, but since they will make it mainstream, this will change the advertising game in a major way.

Published originally on LinkedIn on September 21, 2017

SharePoint Website: The pursuit of agile application development

In the last piece, we saw how to speed up the development of visual components using the content editor web part with HTML5, CSS3, Bootstrap and JavaScript while avoiding the resultant downtime from frequent updates which are part and parcel of any design development project. The Next step was to move to JQuery as it made our code concise and easy to manage, it gave us a more powerful wrapper for AJAX, which we used to access data in SharePoint lists via it’s REST APIs, this was the point where we made the leap from mere front-end development to application development, all with the help of a few lines of code in plain old text files.

Angular JS with its single page application was a perfect fit for us because it was light weight and worked like a charm within Microsoft SharePoint.

Using AJAX to pull information from SharePoint lists made everything very user-friendly, we were able to access information from SharePoint’s lists, which was a big improvement since our users didn’t need to update the ‘text files’ at the back, but they could make changes to the content in the lists and see the results immediately. In case we required two-way data binding between the UI and our application logic and more functionality and play within the visual component, we moved on to Angular JS.

How do we make applications faster? Better?

With a typical requirement of displaying a bunch of data on the screen, let the user search and filter through it dynamically.

Traditional approach would be

Development

  • Develop, Build solution, move the WSP & deploy web-part

Processing

  • If the complete data set is too large, the page can take a lot of time to load initially, AJAX can speed up this time
  • Upon a search/filter query, a server trip would return the filtered result
  • Upon each press of the search button, a resulting server trips adds delays and results in more processing to be done at the back end

Maintenance

  • Any change to the application would mean development – retract and deploy with downtime

The same example with a single page application (SPA) using Angular JS would mean:

Development

  • Develop on text file – plug into any content editor

Processing

  • The page loads up while the AJAX call is busy in fetching the latest data, put up a loading gif while he waits for data
  • The user can use a variety of filters, search queries and see their request updated in real-time on the client’s browser. No server trip, no wait time, no frustration.

Maintenance

  • Any change to the application would mean changes to the text files meaning no downtime for updating the application.

Two-way data processing

Gathering information from users on a form works just as well as getting data from a SharePoint list and displaying it on the page. Angular JS with its powerful client-side validations and processing can mean improved UI/UX along with the incredible maintenance aspect which was the goal all along.

Published originally on LinkedIn on August 11, 2016