Sunday, December 16, 2018

Redux Working - 2. Retrieve Redux Data - mapStateToProps

How to Fetch Redux Data ?


Purpose: Want to fetch THE SM STORE data (What is THE SM STORE?)

Our whatsapp analogy says to read/fetch data of any components
from STORE (group), it needs to be CONNECTED.

Unable to understand above line, go through what is Redux.

REACT-REDUX provides really easy way to connect to THE STORE...

Step 1: Import connect() method from react-redux.

import { connect } from 'react-redux'

Step 2: connect the component which wants STORE data.

export default connect(mapStateToProps, mapActionToProps)(OurComponent)

But wait a minute what are these mapStateToProps, mapActionToProps ?
Let’s Understand via analogy...
How our neighbourhood supermarket/store help us get the required item in easy way:
1. They employ helpers to help us get the right item.
2. They have sign boards hanging, for us to reach at right row to fetch required item.
3. They provide scanners to get right weight and price.
POINT TO NOTE:
These helper tools don’t do anything by themselves, Once you visit the STORE,
you have to summon them to avail the services.
(sounds like dark lord summons the spirits to do the work… scary... :))

Same as our neighbourhood store, REDUX STORE also provides two helper methods called

1. mapStateToProps.

2. mapActionToProps.

And just like normal store, these helper methods do not do anything without summoning them i.e.
1. you have to call them (override them) in your component and
2. tell them explicitly what do you want.
By adding below code in our component , we are summoning mapStateToProps
          const mapStateToProps = () => {
anyVarName: state.componentXData
}
And what helper is doing:
1. Mapping some store state data to local variable.
2. Adding that local variable into component props.
3. And hurrey!!!! we have access to the required data via props.anyVarName
anywhere in the component.

In essence mapStateToProps as name suggests take explicitly stated state
data from THE STORE and adds them into component props.
i.e. In our above example we are accessing componentXData from THE STORE and
adding it into props variable named anyVarName.
which is accessible within OurComponent as props.anyVarName.
Isn’t it awesome…
To conclude:
If you want to get any STORE data in you component, do below
1. Connect() the component
2. Summon(override) mapStateToProps
3. And boom you have data as props in your component
It can’t be made more easier then that….

You must be thinking out loud, how can I conclude...
we still have to demystify mapActionToProps…
Yes we will, that is our next topic Creating and Deleting THE SM STORE Data


Previous: THE SM STORE  Next: Create/Delete Redux Data

Redux Working - 1. Creating THE SM STORE

How Redux works ?

If you are coming directly to this page, I would suggest you to read what is Redux, to better understand the analogy I am using to explain ‘How Redux Works’.

As we understood, In Redux we have something called STORE, which CONTAINS the STATE info of every CONNECTED component.

If you are unable to understand above line, go through what is Redux.

So the STORE is something which manages the states, let me call it THE State Management (SM) STORE.

Let’s create THE SM STORE first and make it accessible to our app components.

In REACT It’s really simple and izzy-pizzy to create store - use createStore() method provided by react-redux library.

1. install react-redux for your application:
              sudo npm install react-redux -g

2. import react-redux in your component
             import createStore from ‘react-redux’

3. create a store :
             let store = createStore();

Damn easy, isn't it...
We have opened/created our store, but how application components will use it ?

Just like normal store... via entry exit doors.

Redux is so simple that it names entry exit doors as PROVIDER.

In below code snippet <ourApp> has been provided access to the store.
Once app is inside the STORE, it can perform all permitted operations (Create Retrieve Delete)

<Provider store = {
  }>
               <OurApp/>
</Provider>

I will break the Redux working into basic CRUD operation.

Create : Create component's state in THE SM STORE.

Retrieve : Fetch component's state from THE SM STORE.

Update : REDUX 2nd Principle says STATE is read only, so no update allowed

Delete: Remove the component's state info from THE SM STORE.

Sunday, December 9, 2018

Redux - Whatsapp group of React Components


What is Redux ?

Before I answer, you first answer to my few questions....

How many family members do you have ? 

2, 3, 4 ?

if you are Asian, might be 6, 8,10, 12, as Asians stay together.

What a weird question, isn't it ? 

Here is my another question...

How do you know about each other ?
i.e. who is doing how ? how is their work ? how is their health ? how are the kids studies ?

you could easily answer these, as you stay in same house or you are so well communicated, that you know about each of them. well that's nice... I am expecting the world should be like this :).

However we are not in that kind of world (I am not), we are so busy with our work, cellphone, TV, friends that we don't get time to talk to all relatives.

However still you want to know about them, but how ?

Simple solution, talk to your Mom (I do), as she is at home and connects to each and every person regularly, she knows almost of everyone.

Now here is the catch, I wanted to know about my in laws ? 

Again a simple solution, I talk to my wife and she gives update for all of them.

But wait a minute she also works, she also doesn't have time to talk to each member of her family, her source of info is also the same i.e. her mom.


to



Are you thinking, what this guy is doing ? 

in this connected world, where we have whatsapp, lync, facebook and so many other mediums to connect, why he is getting info via mom and wife ?

Let's assume, I am not on social media (I hate it, it steals my privacy).

Now information has to flow physically, through people...

Information flow rule says if more and more mouths (layers) are involved to pass info:
1. Chances of stale (outdated) information is very high.
2. Chances of different information for same person (race condition) is very high etc...

To avoid this, what could be the solution:

Solution 1: We all install whatsapp. Create a family group. All connects to the group and every person updates of themselves in that group.

Solution 2: I talk to each and every person to get updates ( too much time consuming ).

Solution 1 looks efficient, whatsapp group ensures:

1. To have a single place where each and every member updates about themselves.
2. Each member can only update about themselves only.
3. The information is read only, no one can update it.
4. The only way to provide new information is via writing new updates, they can not edit the old info.
5. I must connect to group to get the info.
6. Based on the person selection we can get him/her information. lets suppose whatsapp has that functionality. (Definitely whatsapp, will be working on some plan to have filtered info).

Doesn't relational life became simple...

Basically REACT is for single page applications, where a single page contains all the functionalities.
e.g. Youtube page contains player, progress bar, comments, playlist, subscribe and so on... everything on single page, no need to navigate anywhere else.

Each individual functionality is build as separate component. All components are connected, they share data. Changes in one component impacts the other component or other component has to REACT accordingly for SPA(single page application) to work effectively.

Doesn't it sound like my relational life, each family member (each component) wants to know about the STATE of other family member (other components) to REACT accordingly, to get a peaceful and satisfying life (effective application).

Let's ask components to install whatsapp, create a family group and become member of the group :)

For SPA, whatsapp is REDUX and group is STORE. Store holds STATE info of each and every member i.e. connected component.

Just like whatsapp has few rules, REDUX also has 3 principles:

1. Store is the single source of truth 

Just like members details in whatsapp group is single source of true information for everyone part of that group, for REACT application REDUX STORE is true single source of STATE information of each CONNECTED component.

2. State in Store is Read Only

Just like whatsapp, where no one can update anyone else info, its read only. In REACT the STATE info of each component in STORE is read only.

3. Store changes are done using pure function (what are pure functions ?)

In whatsapp, if any member wants to give update, he/she cannot change the old update, he/she has to write a new message with all the new updates (which might contain old info as well). For all members this new update is the latest status of that member.

Similarly any STATE changes in STORE should be by
1. Creating a new STATE ( might be copying the old state data as well ).
2. Updating the STORE with new STATE using pure functions. 


Hope this answered the question what is REDUX ? 

I am writing how REDUX works, will post it very soon as part of REDUX series.

Come back again after few days, till then bye...





Wednesday, December 5, 2018

Pure vs Impure Function in javascript

What is Pure ?

Pure is something, which doesn’t contain anything except itself, it is real in itself. If you check the quality of pure product taking any random sample, results will be always the same.


In Javascript pure function is something, which doesn’t change any external data/state/configuration and if you provide same input it will return the same output.


e.g.
// pure function

function sum(a,b) {
            return a+b;
}

function increment(state) {
           return state.value +1 // not changing the state, just using it
}


// impure function

function setState((prevState, props) => {
           return { prevState.value: props.value }  // changing the state
}


function sum (a,b) {
            someDbCall(a); // doing external things
            someRestUpdateCall(b); // doing external things
            return a+b;
}

Saturday, December 1, 2018

Promise() and Async Await in React


What is Promise?

In general world, when we talk about promise, it is some event which is happening in future.
We just keep a tab somewhere in our mind about that promise, and keep doing our regular work. Once that promise is fulfilled, we get rewards or result of that promise.

e.g. My father promised me and my sister, if we get more than 90 marks in maths, He will buy me a carom board and pink bicycle to her.

Promise din’t stop our daily routine or work, when our result was out and as she scored 98, she got bicycle (promise resolved) and I got 67 marks, I got nothing (promise rejected).

Similarly in JavaScript promise is something which is not going to happen immediately, so program is continuously doing other things, and once promise is resolved or rejected, take the action accordingly.

function reward(marks) {
               return new Promise((resolve, reject) => {
                              if (marks > 90) {
                                             resolve({data: ‘you will get reward as promised’})
                              } else {
                                             reject({data: ‘no gifts’})
                              }
});
}

function isRewarded(marks) {
               this.reward(marks).then ((response) => {
                              console.log(response.data)
               }).catch((error) => {
                              Console.log(error.data)
               });
}
render() {
               this.isRewarded(this.props.marks);
   console.log(‘We are eating our breakfast’);
   console.log(‘We are getting ready for school’);
}

If isRewarded() is run against my marks, output will be :
‘We are eating our breakfast’
‘We are getting ready for school’
‘no gifts’

If isRewarded() is run against my sister marks, output will be :
‘We are eating our breakfast’
‘We are getting ready for school’
‘you will get reward as promised’


New JavaScript standards simplified it further, no need to write then() just use await and async.
1.      Make function async which has to wait for the promise in our case it is isRewarded function.
2.      Put await in front of the function call, which is returning promise.
3.      Done.

Above code with async await will be:

function reward(marks) {
               return new Promise((resolve, reject) => {
                              if (marks > 90) {
                                             resolve({data: ‘you will get reward as promised’})
                              } else {
                                             reject({data: ‘no gifts’})
                              }
});
}

async function isRewarded(marks) {
               let response = await this.reward(marks)
               console.log(response.data);
}

render() {
               this.isRewarded(this.props.marks);
console.log(‘We are eating our breakfast’);
console.log(‘We are getting ready for school’);
}

If isRewarded() is run against my marks, output will be :
‘We are eating our breakfast’
‘We are getting ready for school’

If isRewarded() is run against my sister marks, output will be :
‘We are eating our breakfast’
‘We are getting ready for school’
‘you will get reward as promised’

Did you observe anything ???

For run against my marks nothing printed as part of promise.
The only reason is await async only takes care of positive flow i.e. only resolve() not the reject().
We have to explicitly handle reject() and the simple solution is to put await function call inside try-catch block:

Make below changes and output for my marks will start coming:

async function isRewarded(marks) {
               try {
                              let response = await this.reward(marks)
                              console.log(response.data);
               } catch (error) {
                              console.log(error.data);
               }
}


Hope it helps....

Collabera – CWT – Philippines


The below are my personal views, any of the comments below should not be taken as general.

Different people will have different experiences. These are my personal experiences:


About CWT:

1.      Good Client.
2.      Good work –Majorly Java backend using Boot and front end using React.
3.      Nice work environment ( I like bit of pressure @ work ).
4.      2 weeks sprint and they follow agile process very very seriously.
5.      Have to logically and reasonably explain the carry overs if any.
6.      Keep tab of my each and every activity in terms of what & How I code? What, How, When & Why I commit ? What & Why I mailed ? What & Why I told anything specific ?
7.      Some times over reactive but appreciative as well.
8.      No work from home.
9.      Some teams are very helpful, some are very little. (again personal experience)
10. Around 14-16 Indians services are terminated for performance reasons, as par my knowledge, all are flown back to India as no other opportunities available. I am not in touch of any so don't know what are they doing? till now did they get the job or not, I am not sure...


About Collabera:
1.      Pay on time.
2.      Give answer to each and every query, but takes time to answer.
3.      HR and management are too slow.
4.      Took 1 month to open bank account.
5.      Still waiting for 9G (multi entry visa) after 5 months of coming. Even in case of emergency I have to ask atleast 3-5 people as by myself I cannot visit India, Collabera is having my passport for immigration purposes :( . even if I got my passport with 9G, client has to agree to give me leaves (which are unpaid) and I am agreeing to pay for arranging Business visa again (definitely Collabera is ensuring they will help, no one has tested them yet).
6. Management is responsive but pace of things is slow and most of the time I have to push to get answers and get things done.
7. Sometimes I feel delays are deliberate.

About Philippines:
1.      Scenic country.
2.      Whole country is like Goa of India. ( yes Daru is cheap )
3.      Gorgeous girls.
4.      Very friendly and respecting people.
5.      Many Indians, so will see Indians whichever part of country you go (I tried tourist destinations).
6.      Many Indian Tiffin centres, who will deliver at your work and home place like
       1.  Tajindar foods ( North Indian) :  100 piso par meal including delivery
       2.  Legend foods ( North ) : 150-170 piso par meal including delivery
       3.  Annapurna ( South Indian ) : 200 -250 piso par meal including delivery
       4.  RICH ( South Indian ) : not sure of price, but best I have heard ( never tried )
7.      I stay near WalterMart Makati, it has an Indo Pak restaurant @ 500m, which serves kind of unlimited Indian food @ 130-170 piso, which tastes average.
8.      Many other good Indian restaurants like Bombay house, Queens of Bollywood, Mantra etc.
9.      Many places to get Indian groceries (but @ double price).
10.   Major transportation are AC buses, which are comparatively cheaper.
11.   Very poor country, poverty rate is very high.
12.   Too much pollution and dirtiness, but little better in Makati.
13.   Internet is very costly - upload speed is too - too slow.

Tech Community:
1.      People @ CWT are knowledgeable.
2.      Compare to India, very few good tech companies.
3.      Pay in other companies is not that good, I heard for 8-10 years java experience they pay 40-80K/month. 
4.      CWT is highest paying company, what I have heard in Philippines tech java world (again what I have heard).
5.      I even can’t think to change company as they are paying highest (again it is relative), however pay and opportunities in India are far better than Philippines.
6.      Sometime feel outcast, but it would be same in all countries.