Wednesday, August 7, 2019

How To Hide iPhone or iPad Keyboard When Tapping On The Screen?

To hide or dismiss the keyboard on iPad or iPhone safari browser, you need to lose the focus on your input.
document.activeElement.blur();
With this line you remove the focus and the keyboard disappear.

To be able to hide or dismiss iPhone or iPad keyboard when tapping on the screen, you need to add event on your body. It is possible to recognize touch events on the iPad's Safari browser using jQuery. If you're using jQuery 1.7+ it's even simpler to fix the problem as follows:
$(document).ready(function () {
    $('body').on({
      touchstart: function() {
        if (document.activeElement) {
          document.activeElement.blur();
        }
      }
    });
 });
This detects when you tab the body and then blurs it, so the keyboard will disappear.

Friday, June 28, 2019

How To Scroll To The Top of The Page in React and Typescript?

Issue:
When navigating into another page, its position will remain same like the previous page but you want to scroll to the top of new routed/rendered page.

Solution
I usually put an empty div on top of that page, and gave it a ref, so that, later I can use the scrollIntoView() method to scroll the page into that div.

In TypeScript, you'll have more extra steps to do so, seems to be annoying, but it's actually very helpful because you can take advantages of the type system. First, define a ref like this:
class YourComponent extends React.Component {
  private scrollAnchorRef: any;

  //or private scrollAnchorRef: RefObject<HTMLElement>

  constructor(props) {
    super(props);
    this.scrollAnchorRef = React.createRef(); // Create a ref object 
  }

  render() {
    <div ref={this.scrollAnchorRef}>
      ...
    </div>
  }
}

I have used any type instead of a generic HTMLElement type (recommended) when defining a ref, because it will help the compiler narrow down the type so you'll have better suggestion in the next step.

Now, when you finish rendering/loading page and want to scroll to the top of element, you can do:
  this.scrollAnchorRef.current.scrollIntoView({ block: 'start', behavior: 'smooth' })
And you'll get an error message says: TS2531: Object is possibly 'null'

The reason is, RefObject.current has the type of T | null, because React will actually set an element's ref into null when it re-render, and if you're trying to scroll during re-render, you'll run into problems.

The solution is simple, add an existent check:
 const anchor = this.scrollAnchorRef;
 if (anchor) {
   anchor.current.scrollIntoView({ block: 'start', behavior: 'smooth' }); 
}
Here is the complete solution.

class YourComponent extends React.Component {
  private scrollAnchorRef: any;

  constructor(props) {
    super(props);
    this.scrollAnchorRef = React.createRef(); // Create a ref object 
  }

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      const anchor = this.scrollAnchorRef;
     if (anchor) {
        anchor.current.scrollIntoView({ block: 'start', behavior: 'smooth' }); 
     }
    }
  }

  render() {
   <div ref={this.scrollAnchorRef}>
      ...
   </div>
  }
}

This is how type saved your butt when you work with React and Typescript.

Reference: React, TypeScript and scrollInToView

Monday, May 13, 2019

What Is withRouter And How And When To Use It?

withRouter
You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

Usage of withRouter
If you want that your component will receive Router Props, but don't want to wrap it in <Route component={Some} />. You can just use withRouter function to connect component to the Router, without additional manipulations or jsx tags wrapping. You can just export default withRouter(component)

Explanation/Example
When you include a main page component in your app, it is often wrapped in a component like this:
 <Route path="/movies" component={MoviesIndex} />
By doing this, the MoviesIndex component has access to this.props.history so it can redirect the user with this.props.history.push

Some components (commonly a header component) appear on every page, so are not wrapped in a :
 render() {
   return (<Header />);
 }
This means the header cannot redirect the user.

To get around this problem, the Header component can be wrapped in a withRouter function when it is exported as below:
 export default withRouter(Header)
This gives the Header component access to this.props.history, which means the header can now redirect the user.

Refs: REACT TRAINING / REACT ROUTER / withRouter

Thursday, April 4, 2019

How To Sort Array By Name Or Date In Javascript?

Suppose you have an array users. You need to sort the array by name or date.
var users = [
  {id: 1, firstName: 'Anup', created_date: Mar 12 2012 10:00:00 AM}, 
  {id: 2, firstName: 'Tom', created_date: Mar 8 2012 08:00:00 AM}
];
To sort the array of objects by created_date
Turn your strings into dates, and then subtract them to get a value that is either negative, positive, or zero.
Example:
 users.sort((a, b) => new Date(b.created_date) - new Date(a.created_date));   
To sort the array of objects by firstName
Suppose you have an array users. You may use users.sort and pass a function that takes two arguments and compare them (comparator).
It should return
• something negative if first argument is less than second (should be placed before the second in resulting array)
• something positive if first argument is greater (should be placed after second one)
• 0 if those two elements are equal.

In our case if two elements are a and b, we want to compare a.firstname and b.firstname. When sorting strings toLowerCase() is very important - capital letters could affect your sort.
Example:
users.sort((a, b) => a.firstName.toLowerCase() !== b.firstName.toLowerCase() ? a.firstName.toLowerCase() < b.firstName.toLowerCase() ? -1 : 1 : 0);
If compared strings contain unicode characters you can use localeCompare function of String class like the following:
users.sort((a, b) => a.firstname.toLowerCase().localeCompare(b.firstname.toLowerCase()));

Monday, April 1, 2019

How To Solve Mongo - couldn't connect to server 127.0.0.1:27017 error?

Problem:
[js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:257:13
@(connect):1:6

Solution
Normally this caused because you didn't start mongod process before you try starting mongo shell.

Start mongod server
 mongod
Open another terminal window and start mongo shell
 mongo

Tuesday, March 19, 2019

What Is Difference Between Dot Notation And Bracket Notation?

Accessing Properties on an Javascript Object
There are two ways to work/access properties(key/value pair) on a Javascript object:
• Dot Notation
• Bracket Notation

Dot Notation
Dot notation is used most frequently. Let's first look at Dot notation. Consider this example below:
let person = {
  name: 'Anup',
  age: 34
};
Here is a person object with 2 properties name and age. Let's say we need to change the name of the person, so we need to access the name property of an object Person. We can use dot notation as below
 person.name = 'John';
 console.log(person); // {name: 'John', age: 34}

 console.log(person.name); // John
This is an example of dot notation. You can change properties on an object by specifying the name of the object, followed by a dot (period) followed by the property name person.name = 'John'. Similarly we can use the dot notation to read the value of property like person.name.

Bracket Notation
You can access properties on an object by specifying the name of the object followed by the property name in brackets.
 person['name'] = 'Doe';
 console.log(person); // {name: 'Doe', age: 34}
When working with bracket notation, property identifiers only have to be a String. They can include any characters, including spaces. Variables may also be used as long as the variable resolves to a String.

Dot Notation Vs Bracket Notation
Dot notation is bit concise, shorter and much easier to read than bracket notation and is therefor used more often.

• However, bracket notation has its own uses. Sometimes you don't know the name of the target property until the runtime. With dot notation, we can’t use dynamic variables. For example, in our user interface, user might be selecting the name of the target property dynamically.
 let selection = 'name';
 person[selection] = 'Donald';
 console.log(person); // {name: 'Donald', age: 34}
In that case, at the time of writing the code we don't know that what property we're going to access. That is going to be selected at runtime by the user so might have another variable somewhere else like selection that determines the name of the target property that the user is selecting and that can change at the runtime. We can access that property using the bracket notation in a dynamic way so we can pass selection here and we get the same result in the console.

• It is okay to use variables, spaces, and Strings that start with numbers in the bracket notation i.e. obj['1prop'], obj['prop name'] where as in dot notation, property identifiers cannot start with a number and cannot contain variables and can only be alphanumeric (and _ and $) i.e. obj.prop_1, obj.prop$.

dot notation is mostly assuming the existence of the variables if there is no intellisense while with the bracket notation there is a sense of consciousness which is good, because you really to know what you are dealing with.

• One other advantage of bracket notation. If you flatten an object so that all variables are at the root of your object but you retain the dot in the variable name to represent the properties depth you can use bracket syntax: someObject['propCollection.property']

Reference: JavaScript Quickie— Dot Notation vs. Bracket Notation

How To Make Simple Stopwatch Using Plain Javascript?

In the plain javascript you can use factory function or construction function to create an object.

Let's create a stop watch example to show how to a create a construction function. It has three methods start, stop and reset and private variables are defined as startTime, endTime, running and duration. Also it is defined readonly property called duration using Object.defineProperty method. this keyword is being used to set the properties of an object Stopwatch.
function Stopwatch() {
    let startTime = null;
    let endTime = null;
    let running = false;
    let duration = 0;

    this.start = function() {
        if (running) {
            throw new Error('Stopwatch has already started.');
        }

        running = true;

        startTime = new Date();
    };

    this.stop = function() {
        if (!running) {
            throw new Error('Stopwatch is not started yet.');
        }

        running = true;

        endTime = new Date();

        const seconds = (endTime.getTime() - startTime.getTime()) / 1000;
        duration += seconds;

    };

    this.reset = function() {
        startTime = null;
        endTime = null;
        running = false;
        duration = 0;
    };

    //readonly property
    Object.defineProperty(this, 'duration', {
        get: function() {
            return duration;
        }
    });

}
In your browser's console log, you can run this example as below
const sw = new Stopwatch();

sw.start()
sw.stop()
sw.duration
sw.reset()

Source: Object-oriented Programming in JavaScript: Made Super Simple | Mosh | Stop watch Exercise

Monday, March 18, 2019

Four Pillars of Object Oriented Programming in Javascript

Four Pillars of Object-oriented Programming (OOP)
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism

Encapsulation
In object-oriented programming we group related variable and functions that operate on them into objects and it is called encapsulation. Let's look at the example.
let employee = {
 baseSalary: 30000,
 overtime: 10,
 rate: 20,
 getWage: function() {
   return this.baseSalary + (this.overtime * this.rate)
 }
};
employee.getWage();
We don't have any parameters in the getWage function is because all these parameters are actually modelled as properties of this object. All these properties and getWage function are highly related so they are a part of one unit (i.e employee object). In object-oriented way, your functions end up having fewer and fewer parameters. If fewer the number of parameters the easier it is to use and maintain that function so this is called encapsulation.

Encapsulation gives a couple of benefits as follows.
• Reduce Complexity - We group related variables and functions together and this way we can reduce complexity.
• Increase reusability - We can reuse these objects in different parts of a program or in different programs.

Abstraction
Think of DVD player as an object. This DVD player has a complex logic board on the inside and a few buttons on the outside that you interact with. You simply press the play button and you don't care what happens on the inside. All that complexity is hidden from you. This is abstraction in practice. We can use same technique in our objects so we can hide some of the properties and methods from the outside and this gives a couple of benefits.

• Simple Interface - We'll make the interface of those objects simpler. Understanding an object with a fewer properties and methods is easier than on object with several properties and methods.
• Reduce Complexity - With abstraction, we hide the details and the complexity and show only the essentials. This technique reduces complexity.
• Reduce or isolate the impact of change - Let's imagine that tomorrow we change inner or private methods of the object. None of these changes will leak to the outside because we don't have any code that touches these methods outside of their content object. We may delete a method or change its parameters but none of these changes will impact the rest of the applications code. So with abstraction we reduce the impact of change.

Inheritance
Inheritance is a mechanism that allows you to eliminate redundant code. Here is an example to think of HTML elements like text boxes, drop-down lists, checkboxes and so on. All these elements have a few things in common.

It should have properties like hidden and inner HTML and methods like click and focus. Instead of redefining all these properties and methods for every type of HTML elements we can define them once in a generic object. Lets called it HTML element and have other objects inherit these properties and methods.

Benefit: With inheritance we can eliminate redundant code.

Polymorphism
Poly means many and morph means form. Polymorphism means many forms. In object-oriented programming polymorphism is a technique that allows you to get rid of long if-and-else or Switch-case statements. So back to our HTML elements example, all these objects should have the ability to be rendered on a page but the way each element is rendered is different from others.

If we want to render multiple HTMl elements with object orientation, we can implement a render method in each of these objects and render method will behave differently depending on the type of the object viewer referencing. We can use one line of code like this element.render();

Benefit: With polymorphism we can refactor ugly switch case statements.
Source: Object-oriented Programming in JavaScript: Made Super Simple | Mosh Hamedani

Friday, March 15, 2019

Different Ways of Handling Forms in React

There are two types of form input in react. We have the uncontrolled input and the controlled input. The uncontrolled input are like traditional HTML form inputs, they remember what you typed. We will use ref to get the form values.

Travel form Challenge
You just started your own airline, and you need to create a form to collect data about your passengers' upcoming travel plans so they can book their flight.
You should collect the following information from the user:
First name (text input)
Last name (text input)
Age (number input)
Message (textarea)
Gender (radio buttons with 2 or more options)
Location they're traveling to (select box with at least 3 options. You're an airline that doesn't fly to many places...)
• Whether they have any dietary restrictions (check boxes for vegetarian, kosher, lactose free, etc. Include at least 3 options)

Each element of the form should be given a name attribute so you can access the data in JavaScript and do stuff with it. There should also be a button at the end of the form to submit it.

This exercise is adapted from the V School curriculum on vanilla JS forms:
https://coursework.vschool.io/travel-form

Remember to use the concept of controlled forms https://reactjs.org/docs/forms.html and uncontrolled forms(Refs and the DOM) https://reactjs.org/docs/refs-and-the-dom.html

#1 A controlled input form
The controlled input is when the react component that renders a form also controls what happens in that form on subsequent user input. Meaning, as form value changes, the component that renders the form saves the value in its state.

Controlled components are heavy duty. The defining characteristic of a controlled component is the displayed value is bound to component state; to update the value you execute a function attached to the onChange event handler on the form element. The onChange function updates the state property, which in turn updates the form element's value.
Fig: React Controlled form handling

import React, {Component} from "react"
class ControlledForms extends Component {
    constructor() {
        super()
        this.state = {
            firstName: "",
            lastName: "",
            age: "",
            message: "",
            gender: "",
            destination: "",
            isVegan: false,
            isKosher: false,
            isLactoseFree: false
        }
        this.handleChange = this.handleChange.bind(this)
    }
    
    handleChange(event) {
        const {name, value, type, checked} = event.target
        type === "checkbox" ? 
            this.setState({
                [name]: checked
            })
        :
        this.setState({
            [name]: value
        }) 
    }
    
    render() {
        return (
            <main className="container">
                <form>
                    <input 
                        name="firstName" 
                        value={this.state.firstName} 
                        onChange={this.handleChange} 
                        placeholder="First Name" 
                    />
                    <br />
                    
                    <input 
                        name="lastName" 
                        value={this.state.lastName}
                        onChange={this.handleChange} 
                        placeholder="Last Name" 
                    />
                    <br />
                    
                    <input 
                        name="age" 
                        value={this.state.age}
                        onChange={this.handleChange} 
                        placeholder="Age" 
                    />
                    <br />

                    <label>
                        <textarea
                            name="message"
                            onChange={this.handleChange}
                            placeholder="Enter message"
                            value={this.state.message}
                        >
                        </textarea>
                    </label>
                    <br />

                    <label>
                        <input 
                            type="radio" 
                            name="gender"
                            value="male"
                            checked={this.state.gender === "male"}
                            onChange={this.handleChange}
                        /> Male
                    </label>
                    
                    <br />
                    
                    <label>
                        <input 
                            type="radio" 
                            name="gender"
                            value="female"
                            checked={this.state.gender === "female"}
                            onChange={this.handleChange}
                        /> Female
                    </label>
                    
                    <br />
                    
                    <select 
                        value={this.state.destination} 
                        name="destination" 
                        onChange={this.handleChange}
                    >
                        <option value="">-- Please Choose a destination --</option>
                        <option value="Sweden">Sweden</option>
                        <option value="Norway">Norway</option>
                        <option value="Denmark">Denmark</option>
                        <option value="Finland">Finland</option>
                    </select>
                    
                    <br />
                    
                    <label>
                        <input 
                            type="checkbox"
                            name="isVegan"
                            onChange={this.handleChange}
                            checked={this.state.isVegan}
                        /> Vegan?
                    </label>
                    <br />
                    
                    <label>
                        <input 
                            type="checkbox"
                            name="isKosher"
                            onChange={this.handleChange}
                            checked={this.state.isKosher}
                        /> Kosher?
                    </label>
                    <br />
                    
                    <label>
                        <input 
                            type="checkbox"
                            name="isLactoseFree"
                            onChange={this.handleChange}
                            checked={this.state.isLactoseFree}
                        /> Lactose Free?
                    </label>
                    <br />
                    
                    <button>Submit</button>
                </form>
                <hr />
                <h2>Entered information:</h2>
                <p>Your name: {this.state.firstName} {this.state.lastName}</p>
                <p>Your age: {this.state.age}</p>
                <p>Your Message: {this.state.message}</p>
                <p>Your gender: {this.state.gender}</p>
                <p>Your destination: {this.state.destination}</p>
                <p>Your dietary restrictions:</p>
                
                <p>Vegan: {this.state.isVegan ? "Yes" : "No"}</p>
                <p>Kosher: {this.state.isKosher ? "Yes" : "No"}</p>
                <p>Lactose Free: {this.state.isLactoseFree ? "Yes" : "No"}</p>
                
            </main>
        )
    }
}

export default ControlledForms

The goal is that each time the input changes, the method handleChange is called and will store the input state. Hence the component always has the current value of the input without needing to ask for it. This means that the form component can respond to input changes immediately.

To be able to handle multiple form inputs, we need a way to capture the input with a method instead of declaring multiple methods to do this. Hence we are creating dynamic handleChange method so that our form input can reference it to update it states dynamically.

The value of the name attribute on each input must be the same with the state name declared in the formControls in the constructor.

#2 A uncontrolled input form
An easier, and less labor-intensive way to grab values from a form element is to use the ref property in the form itself.
import React, {Component} from "react"
class UncontrolledForms extends Component {

    handleSubmit = (event) => {
        event.preventDefault();
        const { firstName, lastName, age, message, gender, destination, dietary_restriction } = this.form;

        // convert node list to an array
        const dietaryRestrictionCheckboxArray = Array.prototype.slice.call(dietary_restriction);
        // extract only the checked checkboxes
        const dietaryCheckedCheckboxes = dietaryRestrictionCheckboxArray.filter(input => input.checked);
        // use .map() to extract the value from each checked checkbox
        const dietaryCheckedCheckboxesValue = dietaryCheckedCheckboxes.map(input => input.value);

        const data = {
            firstName: firstName.value,
            lastName: lastName.value,
            age: age.value,
            message: message.value,
            gender: gender.value,
            destination: destination.value,
            dietaryOptions: dietaryCheckedCheckboxesValue
        }

        //alert(JSON.stringify(data));
        console.log(data);
    }
    
    render() {
        return (
            <main className="container">
                <form onSubmit={this.handleSubmit} ref={myform => this.form = myform}>
                    <input name="firstName" placeholder="First Name" />
                    <br />
                    
                    <input name="lastName" placeholder="Last Name" />
                    <br />
                    
                    <input name="age" placeholder="Age" />
                    <br />

                    <textarea name="message" placeholder="Enter message"></textarea>
                    <br />

                    <input type="radio" name="gender" value="male"/> Male
                    <br />
                    <input type="radio" name="gender" value="female"/> Female
                    <br />

                    <select name="destination">
                        <option value="">-- Please Choose a destination --</option>
                        <option value="Sweden">Sweden</option>
                        <option value="Norway">Norway</option>
                        <option value="Denmark">Denmark</option>
                        <option value="Finland">Finland</option>
                    </select>
                    <br />
                    
                    <input type="checkbox" value="vegan" name="dietary_restriction"/>Vegan?
                    <br />
                    <input type="checkbox" value="kosher" name="dietary_restriction"/>Kosher?
                    <br />
                    <input type="checkbox" value="lactoseFree" name="dietary_restriction"/>Lactose Free?
                    <br />
                    <button>Submit</button>
                </form>
                <hr />
            </main>
        )
    }
}

export default UncontrolledForms



Different ways of using refs on form elements
Different form elements and component compositions require different strategies, so the rest of this post is divided into the following sections.

i. Text & number inputs, selects
Text and number inputs provide the most straightforward example of using refs. In the ref attribute of the input, add an arrow function that takes the input as an argument.
<input  
  type="text"
  ref={input => this.fullName = input} />
Since it's an alias for the input element itself, you can name the argument whatever you'd like:
<input  
  type="number"
  ref={cashMoney => this.amount = cashMoney} />
ii. Radio sets
Unlike text and number input elements, radios come in sets. Each element in a set has the same name attribute, like so:
There are two options in the gender radio set – 'male' and 'female'.

Since the whole set is the object of our concern, setting a ref on each radio input is not ideal. And, unfortunately, there's no DOM node that encapsulates a set of radios.

Retrieving the value of the radio set can be obtained through three steps:
1. Set a ref on the <form> tag
2. Extract the set of radios from the form. In this case, it is the gender set
3. Grab the value of the set using dot notation

iii. Checkbox sets
Unlike a radio set, a checkbox set may have multiple values selected. This makes extracting these values a little more complicated than extracting the value of a radio set.

Retrieving the selected values of the checkbox set can be done through these five steps:
1. Set a ref on the <form> tag.
2. Extract the set of checkboxes from the form.
3. Convert the node list to an array, so array methods are available.
4. Use Array.filter() to grab only the checked checkboxes.
5. Use Array.map() to keep only the values of the checked checkboxes.


The primary value of using refs over controlled component is that, in most cases, you will write less code. The exceptional case is that of checkbox sets (and radios to a lesser degree). Source: Learn React for free
Travel Form Challenge
React.js Forms: Using Refs
The complete guide to Forms in React

Tuesday, March 5, 2019

How To Handle Events in React - Different Way vs Best Way?

In the Facebook docs, you’ll see event handling done like this:
// option 1
class Thing extends React.Component {
  constructor() {
    this.handleSmthng = this.handleSmthng.bind(this)
  }
  render() {
    <input onChange={this.handleSmthng}/>
  }
  handleSmthng(e) {
    // ...
  }
}
ES6 classes won’t automatically give this scope to handleSmthng, and since you’ll usually want to call this.setState or perhaps invoke another method in the component, the “official” convention is to bind all the event handlers all the time in constructor. This works, but can quickly feel like boilerplate code.
// option 2
class Thing extends React.Component {
  render() {
    <button onClick={() => this.handleSmthng('foo')}>
      ADD
   </button>
  }
  handleSmthng(arg1) {
    // ...
  }
}
It will pass this context to handleSmthng and it avoids boilerplate code in the constructor. Heck, there’s no state in this component so you don’t even need a constructor! I think the motivations for this approach are right… but there’s a slight performance cost. Using an arrow function will always create a new reference in JavaScript which, in turn, increases memory usage for your apps. While memory is cheap in JavaScript, renders are costly in React. When you pass arrow functions to child components, your child component will indiscriminately re-render since (as far as it’s concerned) that arrow function is new data.

There’s a much cleaner way to write event handlers that
1) avoids boilerplate and
2) doesn’t cause extra re-renders: property initializer syntax!
It’s a fancy name, but the idea is really simple… just use arrow functions to define your event handlers. Like this:
class TodoApp extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>
          ADD
        </button>
        <input onChange={this.handleInput}/>
      </div>
    );
  }
  handleClick = () => {
    // "this"
  }
  handleInput = (e) => {
    // "this", "e"
  }
}
You defined two handlers, and it’s looking really nice. No boilerplate. Easy to read. Easy to re-factor… if you want to pass arguments:
class TodoApp extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>
          ADD
        </button>
        <input onChange={this.handleInput}/>
        {
          this.state.todos.map((item) => {
            return (
              <li onClick={this.handleRemove(item.id)}>
                {item.text}
              </li>
            );
          });
        }
       {
    // "this"
  }

  handleInput = (e) => {
    // "this", "e"
  }

  handleRemove = (id) => (e) => {
    // "this", "e", "id"
  }
}
You can pass arguments without using bind in your render methods, or your constructor! Everything looks really spick and span.
Source: A New Way to Handle Events in React

Monday, February 25, 2019

How to loop through object of objects and add new key-value data using Javascript?

Consider you have an array of summer fruits as below:
  let summerFruits = ['apples', 'bananas', 'mangoes'];
and object of objects as below:
 let obj = 
   { 
       0:
        { 
            name: 'apples'

        },
       1:
        {
             name: 'bananas'
        },
       2:
        {
             name: 'apples'
        },
       3:
        {
             name: 'oranges'
        }
    }
Problem:
You need to add new key/value season: 'summer' to existing object, if it exists summer fruits only.

Solution
You can use JavaScripts' Object.keys to loop through object of objects and findIndex to find the key or index that matches your condition and update the object by an key.
  let summerFruits = ['apples', 'bananas', 'mangoes'];
  let obj = 
   { 
       0:
        { 
            name: 'apples'

        },
       1:
        {
             name: 'bananas'
        },
       2:
        {
             name: 'mangoes'
        },
       3:
        {
             name: 'oranges'
        }
    };

   Object.keys(obj).forEach(key =>
        summerFruits.findIndex(fruit => fruit === obj[key].name) > -1 ?  obj[key].season = 'summer' : ''
   );

   console.log(obj);

//Output
/* {0: {…}, 1: {…}, 2: {…}, 3: {…}}
 0: {name: "apples", season: "summer"}
 1: {name: "bananas", season: "summer"}
 2: {name: "mangoes", season: "summer"}
 3: {name: "oranges"} 
*/

Monday, February 11, 2019

Understanding Redux - For Absolute Redux Beginners

The official documentation for Redux reads: Redux is a predictable state container for JavaScript apps.

Explaining Redux: For Absolute Redux Beginners

These bank terms are used in the article that is equivalent to Redux terms:
1. Bank Vault = Redux Store
2. Intent(i.e. withdraw money) = Redux action
3. Cashier = Redux Reducer
4. Money = State

Let’s consider an event you’re likely familiar with — going to the bank to withdraw cash. Even if you don’t do this often, you’re likely aware of what the process looks like.

You wake up one morning, and head to the bank as quickly as possible. While going to the bank there’s just one intention / action you’ve got in mind: to WITHDRAW_MONEY.

When you get into the bank, you then go straight to the Cashier to make your request known.

Wait, you went to the Cashier? Why didn’t you just go into the bank vault to get your money?

Well, like you already know, things don’t work that way. Yes, the bank has money in the vault, but you have to talk to the Cashier to help you follow a due process for withdrawing your own money.

The Cashier, from their computer, then enters some commands and delivers your cash to you. Easy-peasy.

Now, how does Redux fit into this story?

We’ll get to more details soon, but first, the terminology.

1. The Bank Vault is to the bank what the Redux Store is to Redux.
The bank vault keeps the money in the bank, right?

Well, within your application, you don’t spend money. Instead, the state of your application is like the money you spend. The entire user interface of your application is a function of your state.

Just like the bank vault keeps your money safe in the bank, the state of your application is kept safe by something called a store. So, the store keeps your 'money' or state intact.

The Redux Store can be likened to the Bank Vault. It holds the state of your application — and keeps it safe.

This leads to the first Redux principle:
Have a single source of truth: The state of your whole application is stored in an object tree within a single Redux store.
In simple terms, with Redux, it is is advisable to store your application state in a single object managed by the Redux store. It’s like having one vault as opposed to littering money everywhere along the bank hall. Redux first principle 2. Go to the bank with an action in mind.

If you’re going to get any money from the bank, you’re going to have to go in with some intent or action to withdraw money.

If you just walk into the bank and roam about, no one’s going to just give you money. You may even end up been thrown out by the security. Sad stuff.

The same may be said for Redux.

Write as much code as you want, but if you want to update the state of your Redux application (like you do with setState in React), you need to let Redux know about that with an action.

Now, this leads to Redux principle #2.
State is read-only: The only way to change the state is to emit an action, an object describing what happened.
What does that mean in plain language?

When you walk to the bank, you go there with a clear action in mind. In this example, you want to withdraw some money.

If we chose to represent that process in a simple Redux application, your action to the bank may be represented by an object.

One that looks like this:
{ 
  type: "WITHDRAW_MONEY",
  amount: "$10,000"
}
In the context of a Redux application, this object is called an action. It always has a type field that describes the action you want to perform. In this case, it is WITHDRAW_MONEY.

Whenever you need to change/update the state of your Redux application, you need to dispatch an action. Redux second principle Don’t stress over how to do this yet. I’m only laying the foundations here. We’ll delve into lots of examples soon.

3. The Cashier is to the bank what the reducer is to Redux.

Alright, take a step back.

Remember that in the story above, you couldn’t just go straight into the bank vault to retrieve your money from the bank. No. You had to see the Cashier first.

Well, you had an action in mind, but you had to convey that action to someone — the Cashier — who in turn communicated (in whatever way they did) with the vault that holds all of the bank’s money.

The same may be said for Redux.

Like you made your action known to the Cashier, you have to do the same in your Redux application. If you want to update the state of your application, you convey your action to the reducer — our own Cashier.

This process is mostly called dispatching an action. In this example, and in the Redux world, it is used to mean sending off the action to the reducers.

The reducer knows what to do. In this example, it will take your action to WITHDRAW_MONEY and ensure that you get your money.

In Redux terms, the money you spend is your state. So, your reducer knows what to do, and it always returns your new state.

And this leads to the last Redux principle:
To specify how the state tree is transformed by actions, you write pure reducers.
As we proceed, I’ll explain what a “pure” reducer means. For now, what’s important is to understand that, to update the state of your application (like you do with setState in React,) your actions must always be sent off (dispatched) to the reducers to get your new state. Redux last principle With this analogy, you should now have an idea of what the most important Redux actors are: the store, the reducer and an action.

These three actors are pivotal to any Redux application. Once you understand how they work, the bulk of the deed is done.


Summary:
When working with Redux, you will need three main things:
1. actions: these are objects that should have two properties, one describing the type of action, and one describing what should be changed in the app state.
2. reducers: these are functions that implement the behavior of the actions. They change the state of the app, based on the action description and the state change description.
3. store: it brings the actions and reducers together, holding and changing the state for the whole app — there is only one store.

Redux Principles
1) ONE application STATE OBJECT managed by ONE STORE. Have a single source of truth: The state of your whole application is stored in an object tree within a single Redux store.

2) State is read-only: The only way to change the state is to emit an action, an object describing what happened.

3) To specify how the state tree is transformed by actions, you write pure reducers.

Source: Understanding Redux: The World’s Easiest Guide to Beginning Redux by Ohans Emmanuel