-->

  • Add Redux Toolkit in react redux saga

     


     

    Add Redux Toolkit in React Redux Saga

     

    Hello viewers, i am back again for you and now we will start from redux-saga. So, we are ready for implemenation of redux toolkit. Actually we are making some project like E-commerce where we can implement searchbar, product add to cart, remove from cart, empty cart, cart section after adding some product and product section and a lot of things, So, don't worry i'm not going to leave you alone.

     

     

    React


    Certainly, Reactjs is a JavaScript library developed by Facenook for building user interfaces. It allows developers to create reusable UI components and effciently manage the state of their applications. Here are some key aspects of Reactjs.


    Component-Based Architecture: ReactJS follows a component-based architecture, where the user interface is divided into small, reusable components. Components encapsulate their own logic, state, and rendering, making it easier to build and maintain complex user interfaces.



    Virtual DOM: ReactJS uses a virtual representation of the DOM (Document Object Model), known as the Virtual DOM. When the state of a component changes, React updates the Virtual DOM.



    JSX: JSX is a syntax extension for JavaScript used in React. It allows developers to write HTML-like code within JavaScript, making it easier to describe the structure and appearance of components. JSX code is transpiled to regular JavaScript using tools like Babel before being executed in the browser.


    Hooks: React introduced Hooks in version 16.8 as a way to use state and other React features in functional components. Hooks allow developers to write reusable logic and manage state within functional components without the need for class components. The most commonly used hooks are useState for managing state and useEffect for handling side effects such as fetching data or subscribing to events.


    React Router: React Router is a popular routing library for React applications. It enables developers to create single-page applications with multiple views and handles routing between different components based on the URL.


    State Management: React provides a flexible ecosystem of state management solutions. While React's built-in state management (useState ) is suitable for managing local component state, more complex applications may benefit from additional state management libraries like Redux. These libraries help manage global application state and provide predictable ways to update and access the state.


    ReactJS has gained widespread popularity due to its performance, reusability, and declarative approach to building user interfaces. It has large community.

     

    Topic we will cover -


    # Make Action and Reducer in New File

    # Add Redux Toolkit

    # Why we need saga Live Example

     

    Don't Forget to Check - https://www.kumaratuljaiswal.in/2023/09/get-data-in-component-from-redux.html

    Don't Forget to Check - https://www.kumaratuljaiswal.in/2023/11/remove-from-cart-in-react-redux.html

     

    Make Action and Reducer in New File

     

    First we will make a file, ProductAction.jsx , in this file we will add product listing so our return type is PRODUCT_LIST and add in constant file.

     

    Let's add the code.

     

     

    import { PRODUCT_LIST } from "./Constant";
    
    export const productList = () =>  {
        let data = "hello atul"
        console.log("product listing action is called", data)
        return {
            type: PRODUCT_LIST,
            data
        }
    }
    
    
    

     


    Constant.jsx

     

    export const PRODUCT_LIST = "PRODUCT_LIST";
    

     

     




     

    Make Reducer in New File

     

    ProductReducer.jsx - Now we will make a file, ProductReducer.jsx , in this file we will add case whenever user click on some action so trigger the case.


     

    import { PRODUCT_LIST } from './Constant';
    
    export const productData = (data = [], action) => {
        switch(action.type)
        {
            case PRODUCT_LIST:
                console.log("PRODUCT_LIST CONDITION", action)
                return [action.data];
            default:
                return data;
        }
    }
    //www.kumaratuljaiswal.in #www.hackingtruth.in
    

     

     

     

    Register or add the reducer in RootReducer.jsx file

     

    import { combineReducers } from 'redux'
    import { cartData } from './Reducer'
    import { productData } from './ProductReducer';
    
    export default combineReducers({ 
        cartData,
        productData 
    
    })
    
    //www.kumaratuljaiswal.in www.hackingtruth.in
    

     

     

    Still are you in trouble or confused how we add the extra code like combineReducers, cartData, etc, etc, so please visit these below links that we have provided.


    MainHeader.jsx


    Here, we have to import productList from productAction.jsx and adding a button that when user click on it then product listing showing.... 

     


    import { productList } from '../redux/ProductAction';
    
     <div>
               <button
                className="bg-red-700 text-white p-2"
                onClick={() => dispatch(productList())}
              >
                {" "}
                Get Product List
               </button>
             </div>
    



    If we want the result in same page (MainHeader.jsx) when user click on Get Product List button. Suppose that we have already filled the data in the cart section.

    Here we are getting the data of all the products which we have registered in the RootReducer.jsx file

    Like

     cartData,
        productData 



    import { productList } from '../redux/ProductAction';
    
    
      const data = useSelector((state) => state);
      console.log("data in main component", data);
    





    But if we want only product listing's data then we have to add in state...

    state.productData  and in action we have defined static data thats why we got a static data like hello atul.


    Full Code (MainHeader.jsx)



    import React from "react";
    import { addToCart, removeFromCart, emptyCart } from "../redux/Action";
    import { useDispatch } from "react-redux";
    import { productList } from '../redux/ProductAction';
    
    import { useSelector } from "react-redux";
    
    
    function MainHeader() {
      const dispatch = useDispatch();
    
      const data = useSelector((state) => state.productData);
      console.log("data in main component", data);
    
      const product = {
        name: "Motorola",
        type: "mobile",
        price: 18000,
        color: "silver",
      };
    
      return (
        <div>
          <div className="max-w-[1240px] mx-auto mt-6 ml-2 grid lg:grid-cols-4">
            <div>
              <button
                className="bg-green-700 text-white p-2"
                onClick={() => dispatch(addToCart(product))}
              >
                Add to Cart
              </button>
            </div>
    
            <div>
              <button
                className="bg-red-700 text-white p-2"
                onClick={() => dispatch(removeFromCart(product.name))}
              >
                {" "}
                Remove To Cart
              </button>
            </div>
    
            <div>
              <button
                className="bg-red-700 text-white p-2"
                onClick={() => dispatch(emptyCart())}
              >
                {" "}
                Empty Cart
              </button>
            </div>
            
            <div>
              <button
                className="bg-red-700 text-white p-2"
                onClick={() => dispatch(productList())}
              >
                {" "}
               Get Product List
              </button>
            </div>
    
          </div>
        </div>
      );
    }
    //www.kumaratuljaiswal.in    www.hackingtruth.in
    export default MainHeader;
    
    







    Add Redux Toolkit


    We are installing redux toolkit and using this toolkit (RTK) because createStore( ) in Store.jsx file has been removed in redux.


    Store.jsx





    import { configureStore } from "@reduxjs/toolkit";
    import RootReducer from "./RootReducer";
    
    
    const Store = configureStore({reducer: RootReducer})
    
    export default Store
    
    //www.kumaratuljaiswal.in #www.hackingtruth.in
    
    


     

    API Calling (ProductAction.jsx)


    Public API (you can also use this) - http://jsonplaceholder.typicode.com/todos/1

     

     

     

    import { PRODUCT_LIST } from "./Constant";
    
    export const productList = async () =>  {
        //let data = "hello atul"
        let data = await fetch("http://jsonplaceholder.typicode.com/todos/1");
        data = await data.json()
        console.log("product listing action is called", data)
        return {
            type: PRODUCT_LIST,
            data
        }
    }
    
    
    

     

     

    But we got some error - Actions must be plain objects. Instead, the actual type was: 'Promise'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. 

     

    Middleware only two - saga or redux-thunk but we will use saga (it is easy) in the next blog.







     


    # Install redux and saga packages - CLICK HERE

    # Make reducer wrapper - CLICK HERE

    # Action in reducer - CLICK HERE

    # Reducer in redux - CLICK HERE

    # Switch Stmt in redux - CLICK HERE

    # Get data in component from redux - CLICK HERE 

    # Remove from cart - CLICK HERE

     

    Disclaimer



    All tutorials are for informational and educational purposes only and have been made using our own routers, servers, websites and other vulnerable free resources. we do not contain any illegal activity. We believe that ethical hacking, information security and cyber security should be familiar subjects to anyone using digital information and computers. Hacking Truth is against misuse of the information and we strongly suggest against it. Please regard the word hacking as ethical hacking or penetration testing every time this word is used. We do not promote, encourage, support or excite any illegal activity or hacking.

     

     

     

  • 0 comments:

    Post a Comment

    For Any Tech Updates, Hacking News, Internet, Computer, Technology and related to IT Field Articles Follow Our Blog.