Wednesday, April 29, 2020

React Flux with Simple Example

React Java script build by facebook for view part of the MVC. This means it itself did not give or suggest you any frame work to incorporate like Angular which comes with inbuild Framework to build an application. Having said this it becomes important to have a fram work to follow religiously so that project maintainability and scalability can be addressed in long term goal. As in long time after working with any application if no frame work is maintained it will be the main cause of failure along with hard to maintain and understand the project.
Flux is another open source Frame work provided by Facebook and suggested to use in React. As we have MVC framework in java application explained below
Controller :- This is the central hub of the MVC framework. It acts as an intermediate between model and view. Generally we always have one controller per application. Its main function is to handle all the request from the view in terms of action. Controller decide what to do with data either to send it to view part for showing to the user or it need to go to model to perform some DB or REST call.
View :- This represent the view part of the application and never talk directly with Model. It has to go through controller.
Model :- This represent the data that is coming from Controller. It never talk directly with View. It either take data from Controller and perform W/S or DB call or take the data from DB or REST and give to controller by informing to provide it to view for rendering.
Action --> Controller
| |
View Model

Flux is also similar to MVC but unidirectional. It has following part
Action --> Dispatcher --> Store -->View
Lets discuss few of the aspect of all describe above
'- Action send the action using dispatch to dispatcher
'- Dispacther take the action and send the data and action type to store
'- store responds to the dispatched action using register, switch and case.
'- Store finally emits change to view and view update as per the need.
In short user perform the action i.e. clicking on button this action is send to Action class which call the Dispacther class by sending the action type (to differentiate different action) and data and then dispatcher using dispatch this action and data to all the store who has already register them self with this dispatcher. Finally when the data is taken by the store class it perform the operation and send event to View to do changes.
Please refer to the working code as given below

You can also download the code from URL

https://github.com/shdhumale/SimpleReactFluxExample


Folder structure

Iamge1Iamge2Iamge3Iamge4Iamge5Iamge6Iamge7Iamge8Iamge9

Thursday, April 16, 2020

Redux Library and its uses in Java Script

Redux is the third party extension that can be used for any Java script application as third party library.It act as a predictable state container .
Following are the important aspect of the Redux
-> SAR - MA :-
'- Store :- store the state of the Application. Means every application must have single state to be store,
'- Action :- indicate what need to be done with the state which is readonly. Your application must tell redux through/by firing the action to redux from your application telling what need to be done with the state. No Direct update is avaialble,
'- Reducer:- Actully carrier out the change in the state. i.e. we need to write the code in reducer (pure function that teake prevState and action as input) and change the new state depending. so how the state is transfer is depending on this reducer.
In short our application subscribe to redux, it store its state in redux, It cannot change the state directly it has to emit/dispath the action which is given to reducer which is pure function depending on the action type it will modify the state and then redux inform/send the new state to our application as it is subscribed.
'- Store :- CGSD - Create store , Getstate - to get the state of the application, susbcribe(listener) for subscrbing and unsubscribing the listener as the state change and dispatch(action) is used to make change in state in the store.
'-MiddleWare :- It is 3rd party extension act between dispatching the action and receving to reducers. It can be used for log, crash reporting, performing async task etc.
'-Asyn Action :- this is generally achieved using Thunk external library in Redux. It help us to get the action creater to return function instead of action object.
Let take an example or Use case
SAR - State (Data + Error + Loading) , Action (User request, User error, User succssess), Reducer funtion (User request => loading=true, User error => loading = false, error=true , User success =>loading = true, data=User) use axios and thunk(as middleware)
Code As given below
//We are using Axios and Thunk for making REST call using Redux
//As per process we will first follow this three steps
//1- create ActionInitiator
//2- Create Reducers that take state = InitialState and Action as parameters
//3- Create Store
//Our requirement is 1- Mak a ASync Rest call 2- Till the call is working keeping loading parameter true 3- On success (a) keeping loading parameter true and (b) fill the data 4- on error (a) keeping loading parameter true (b)) fill the error with message and (c) make/set the data error as empty
//SAR => I-AIR -ST => CGSD (Store - Action-Reducer => InitialState, Action, ActionInitiator, Reducer, Store - [Createstore, getstate, subscribe, dispatchaction, unsubscribe], thunk Async Function) -
const redux = require("redux")
const applyMiddleware = redux.applyMiddleware
const reduxThunk = require("redux-thunk").default
const axios = require("axios")
//1- Declare initialState
const initialState = {
loading: false,
users: [],
error: ''
}
//2- Create Action
const USER_REQUEST = "USER_REQUEST"
const USER_SUCCESS = "USER_SUCCESS"
const USER_ERROR = "USER_ERROR"
//3- Create Action Initiators
const fetchUserRequest = () => {
return {
type: USER_REQUEST
}
}
const fetchUserSuccess = (users) => {
return {
type: USER_SUCCESS,
payload: users
}
}
const fetchUserError = (error) => {
return {
type: USER_ERROR,
payload: error
}
}
//4- Create Reducers
const reducer = (state = initialState, action) => {
switch (action.type) {
case USER_REQUEST: return {
...state,
loading: true
}
case USER_SUCCESS: return {
loading: false,
users: action.payload,
error: ''
}
case USER_SUCCESS: return {
loading: false,
users: [],
error: action.payload
}
}
}
//6- Create Thunk Async Function this will return a Async function rather than action object as we defined in other action creater. Also this has ability to dispatch the action
const fetchUsers = () => {
return function (dispatch) {
//axios.get('https://jsonplaceholder.typicode.com/users').then(
//axios.get('https://jsonplaceholder.typicode.com/todos').then(
axios.get('https://jsonplaceholder.typicode.com/posts/1').then(
response => {
const users = response.data
dispatch(fetchUserSuccess(users))
}
).catch(
error => {
const errors = error.Message
dispatch(fetchUserError(errors))
}
)
}
}
//5- Create store CGSD
const store = redux.createStore(reducer, applyMiddleware(reduxThunk))
console.log('Initial state', store.getState())
store.subscribe(() => { console.log(store.getState()) })
store.dispatch(fetchUsers())

Redux1