7/11/19

Hooks in React

What is this new React feature everybody is talking about?
Well, it seems the main problem it tries to solve is - how to use state inside functional components.
Functional... what?
Ok, lets start from the beginning:
Usually to build the component with React you should use the following syntax:

class HelloMessage extends React.Component {
  render() {
    return (
      <div>;
        Hello {this.props.name}
      </div>
    );
  }
}

It also called the class syntax
The Interesting thing is - this is not the only way. There is another way to create react component, it called functional :

function Example(props) {
   return  ( 
      <div>;
        Hello {this.props.name}
      </div>
     );
}

This way is much more simpler and clear and testable, because - it is just javascript function!
BUT! (There is always but) - one of the limitations of functional components is - that here you cannot use the "state" feature of React.
State - it is inner data of the component which is not accessible from the parent

class UserForm extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      username:'',
      lastname: ''
    };
  }
  render() {
    return (
      <form>
        username: <input value={this.state.username}/>  <br/>
        lastname:  <input value={this.state.lastname}/>
      </form>
    );
  }
}

ReactDOM.render(
  <UserForm  />,
  document.getElementById('user-form')
);

So now (from React 16.8 and later) you can use state feature event inside functional components (Yes You Can!)- by using following syntax:

import React, { useState } from 'react';

export default function Example() {
    const [userModel, setUserModel] = useState({username:'ss', lastname:'dd'});

    return (
      <form>
        username: <input value={userModel.username}/>  <br/>
        lastname:  <input value={userModel.lastname}/>
      </form>
    );
  }

Note that "setUserModel" is for modify the state:

<button onClick={()=>setUserModel({username: 'shlomo', lastname: 'shlomovitz'})}/>click</button>

Pretty Cool, huh?

7/6/19

Tagged Template Literals

Ok, everybody heard about "backticks" ES6 feature...


 const hero = 'Splinter'
 console.log(`My name is ${hero}`); 
// will print "My name is Splinter"

But recently I stumble upon following code I could not understand:

import { css, cx } from 'emotion'

const color = 'white'

render(
  <div
    className={css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
      border-radius: 4px;
      &:hover {
        color: ${color};
      }
    `}
  >
    Hover to change color.
  </div>
)

What is this strange syntax?

Tagged Template Literals

Well it appears you can tag a template with function
Like this:

 const hero = 'Splinter';

 const printHero = html`My name is ${hero}`;
 // here is the function:
 function html(strings, ...values) {
   let str = '';
   strings.forEach((string, i) => {
       str += `${string} ${values[i] || ''}`;
   });
   return str;
 }

/*
printHero will print:
"My name is  <span class='hl'>Splinter</span> <span class='hl'></span>"
*/

Using tagged template gives you ability to control the way the template is parsed.

6/6/19

When You Should Use Subject

Subject - Who are you?

Yes, lot of us (angular people) have heard about subjects. Yes, it is something that acts like observable (you can subscribe to it):


const subject = new Subject();
...
subject.subscribe(x => console.log(x));

And simultaneously you also can call "next" method, like in observer:

 ...
 const button = document.querySelector('button')
 button.addEventListener("click", () => subject.next('click')); 
 ...

Ok, great, but... when it is good practice to use this Subject thing? you may ask...

Lets look on what Angular guys are Doing

Everybody who starts with "get started" section of angular - knows about "heroes tour" tutorial.
Quick search shows the use of "Subject" in the HeroSearchComponent.
Here you have a pretty common scenario: a search input which have to trigger a search request and populate with response results a list below the input...
So in "input" event handler you expect to see something like this:


  search(term: string): void {
    this.heroService.searchHeroes(term).subscribe(results => this.heroes = results);
  }

Or, when displaying the data using "Async" pipe, something like:

/*    
   <li *ngFor="let hero of heroes$ | async" >
      <a routerLink="/detail/{{hero.id}}">
        {{hero.name}}
      </a>
    </li>
*/
  search(term: string): void {
    this.heroes$ = this.heroService.searchHeroes(term);
  }

The problem with this code (although it will work) - is that the subscription to "searchHeroes" method is done each time when search terms changes, (not mention is already done at "ngOnInit" lifehook of the component):

 ngOnInit(): void {
    this.heroes$ = this.searchTerms.pipe( // pipe is the equivalent of "subscribe"
      // wait 300ms after each keystroke before considering the term
      debounceTime(300),

      // ignore new term if same as previous term
      distinctUntilChanged(),

      // switch to new search observable each time the term changes
      switchMap((term: string) => this.heroService.searchHeroes(term)),
    );
  }

And it is bad to subscribe multiple times, because of memory leaks potential. Instead - by using searchTerms Subject(like Angular guys did), you can call the "next" and trigger the service again, which is much more accurate:

  // Push a search term into the observable stream.
  search(term: string): void {
    this.searchTerms.next(term);
  }
 

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...