Redux - Saga





Redux is a state management tool that works as a “centralized store,” which means that it

is the only place to access the state.Redux is a light “standalone” JavaScript library, which means it can be used with any UI framework, most frequently, it is used with ReactJS.



Redux-Thunk



Redux Thunk is a middleware that enables you to call action creators that return functions (thunks) that accept the store's dispatch method as an argument and are then used to dispatch the synchronous action after the API or side effects have ended.



Redux-Saga


Another middleware library that assists us with API calls or side effects is Redux Saga. Redux Saga makes use of ES6's "Generators" feature, which makes it easier to develop asynchronous code. Redux-saga’s action creator returns an Object while Redux-Thunk action creator returns a Function(thunk).



Redux-Saga Data Flow








How data flow



  1. When a user interacts with the application, an action is dispatched

  2. Root Reducer/ Reducer  function is called with the current state and the dispatched action

  3. Root Reducer may divide the tasks among smaller reducer functions, which ultimately returns s new State 

  4. The store notify the View by executing their callback functions

  5. The view can retrieve updated state and re-render again




How It Works 





Store


Store is the central repository for storing the whole state tree of the application. In a react application, Only one store can be maintained. How to create a store,


Simply, createStore() method in the redux library helps to create a store. However, to create a store, the reducer must be specified.


const store = createStore(reducer);


The createStore() can have up to 3 arguments.


const store = createStore(reducer, preloadedStateenhancer);


Reducer - A reducer is a function that returns the next state of app

Preloader - is optional and the initial state of the application

Enhancer - is optional and will help to enhance store with third-party capabilities



The store has three important methods that interact with it,


getStore() - allows to retrieve the current state of the store


store.getState()


dispatch() - allows to dispatch an action to change the state of the application


store.dispatch({type:'REQUEST_TYPE'})


subscribe() - aids you in setting up a callback that the Redux store will make a call to when an action has been sent. The view will re-render instantly after the Redux state has been updated.


store.subscribe(()=>{ console.log(store.getState());})


To unsubscribe, 


const unsubscribe = store.subscribe(()=>{console.log(store.getState());});

unsubscribe();




Actions


Actions are plain javaScript that must have a type of the action. Other than that the structure of the action can be decided by the developer. But the action type must be defined. To cause any change in the store, an action must be dispatched using store.dispatch().


const ITEMS_REQUEST = 'ITEMS_REQUEST';


The action object can be defined as follows also,


{ type: ‘FIND_USER’ , payload: {username,password } }

{ type: ‘GET_USER’, payload: userId }




Reducer


 Reducers are pure functions in redux, 


It is the only location where computations and reasoning can be written. The reducer function will accept the previous state of the application and the action being sent, compute the upcoming state, and then return the fresh object.


Never carry out the following actions inside the reducer:


  • Arguments for functions can change

  • API requests and routing rules

  • The use of non-pure functions, such as Math.random ()


 

const initialState = [

    {

        id: 0,

        name: "Tharindu",

        number: "0715771284"

    },

    {

        id: 1,

        name: "Kumesh",

        number: "0715771284"

    },

    {

        id: 2,

        name: "Rajitha",

        number: "0715771284"

    }

];

 

const postReducer = (state = initialState, action) => {

    switch(action.type){

        case "ADD_POST":

           state = [...state, action.payload];

           return state;

        case "UPDATE_POST":

            const updatedstate = state.map((post) => post.id === action.payload.id ? action.payload : post );

            state = updatedstate;

            return state;

        case "DELETE_POST":

            const filteredContact = state.filter(post => post.id !== action.payload.Id && post);

            state = filteredContact;

            return state;

        default:

            return state;

    }

}

 

export default postReducer;



The above is an example for a reducer called postsReducer. It has an Initial state called initialState object. The postReducer can take two arguments for the initial state and the action dispatched.





How to use the store


The store can be used anywhere in the application. The useSelector() which is a method provided by react-redux library.


const posts = useSelector(state => state); 

(if the state need to be retired as same as it is)





Comments

Popular posts from this blog

Insertion Sort - Time Complexity

Selection Sort - Time Complextity

Quick Sort - Time Complexity