-->

  • Search product with API in react redux saga

     

    Search product with API in react redux saga

     

    Search product with API


    Hello viewers, i am back again for you and now we will start from redux-saga. So, we are ready for implemenation of Search product with API in react redux saga and set result. 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 Search box and Add style

    # Make Action and Saga

    # Call API for search product

    # Test API result

     

    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

    Don't Forget to Check - https://www.kumaratuljaiswal.in/2023/11/configure-saga-middleware-in-react.html

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

    Don't Forget to Check - https://www.kumaratuljaiswal.in/2023/11/add-routing-and-make-cart-page.html

     


    Make Search box and Add style

     

    We will make a search bar first with tailwind style css in Header.jsx where user can search anything about product. We will use tailwind css for adding style.

     

     Header.jsx

     

     

     <div className="max-w-[1040px] shadow-xl mx-auto min-h-[40px] p-3 ">
            <div className="pt-2">
              <input
                type="search"
                placeholder="Search the Product"
                className="w-full pl-3 pr-3 pt-2 pb-2 border border-blue-700 rounded text-slate-600  "
                 
              />
            </div>
          </div>
    

     

     

     

     

    Search product with API in react redux saga

     

     Make Action and Saga

     

    Now we will make action file (already have been created - please check our previous blog).

     

    ProductAction.jsx

     

    Here we import first PRODUCT_SEARCH as a constant from constant.jsx file and then make const productSearch and inside this arrow function we pass a query this will be useful as a parameter when we search anything from searchbar and return type (same as constant file).

     

     

    import { PRODUCT_SEARCH } from "./Constant";
    
    export const productSearch = (query) => {
        return {
            type: PRODUCT_SEARCH,
            query,
        }
    }
    

     

     


    Constant.jsx


    Search product with API in react redux saga


    Now we will call from header.jsx file



    import { useSelector, useDispatch } from "react-redux";
      import {productSearch } from '../redux/ProductAction';
      
      const dispatch = useDispatch();
      
       <div className="max-w-[1040px] shadow-xl mx-auto min-h-[40px] p-3 ">
            <div className="pt-2">
              <input
                type="search"
                placeholder="Search the Product"
                className="w-full pl-3 pr-3 pt-2 pb-2 border border-blue-700 rounded text-slate-600  "
                onChange={(event) => dispatch(productSearch(event.target.value))}
              />
            </div>
          </div>
      

     

     

    productSaga.jsx

     

     

    function* searchProduct(data) {
        let result = yield fetch(`http://localhost:3000/products?q=${data.query}`);
        result = yield result.json();
        console.log("product search is called", data);
        yield put({type: SET_PRODUCT_LIST, data:result})
    
        if (result.length === 0){
            console.log("not found");
        }
    }
    
    function* ProductSaga() {
     yield takeEvery(PRODUCT_SEARCH, searchProduct)
    
    }
    

     

     

     

    Whole Code (Header.jsx)

     

     

    import React from "react";
    import { BsFillCartPlusFill } from "react-icons/bs";
    
    import { useSelector, useDispatch } from "react-redux";
    import { useNavigate } from "react-router-dom";
    
    import {productSearch } from '../redux/ProductAction';
    
    const Header = () => {
      const result = useSelector((state) => state.cartData);
      console.log("redux data in header", result);
    
      const dispatch = useDispatch();
    
      const navigate = useNavigate();
    
      return (
        <div>
          <div className="bg-[#434be6] p-4 w-full relative">
            <div className=" flex justify-between mx-auto px-2   items-center  ">
              <div>
                <h1
                  className="text-white font-bold cursor-pointer"
                  onClick={() => navigate("/")}
                >
                  E-Commerce
                </h1>
              </div>
    
              <div className="cursor-pointer" onClick={() => navigate("/cart")}>
                <span className="bg-green-500  rounded-xl px-1 absolute text-[12px] top-[9px]  right-7 text-white border border-black">
                  {result.length}
                </span> 
    
                <BsFillCartPlusFill size={30} className="" />
              </div>
            </div>
          </div>
    
          <div className="max-w-[1040px] shadow-xl mx-auto min-h-[40px] p-3 ">
            <div className="pt-2">
              <input
                type="search"
                placeholder="Search the Product"
                className="w-full pl-3 pr-3 pt-2 pb-2 border border-blue-700 rounded text-slate-600  "
                onChange={(event) => dispatch(productSearch(event.target.value))}
              />
            </div>
          </div>
        </div>
      );
    };
    
    export default Header;
    
    

     

     

    Constant.jsx

     

     

    export const  ADD_TO_CART  = "ADD_TO_CART";
    export const  REMOVE_TO_CART  = "REMOVE_TO_CART";
    export const  EMPTY_CART  = "EMPTY_CART";
    export const PRODUCT_LIST = "PRODUCT_LIST";
    export const SET_PRODUCT_LIST = "SET_PRODUCT_LIST";
    export const PRODUCT_SEARCH = "PRODUCT_SEARCH";
    
    
    
    //www.kumaratuljaiswal.in #www.hackingtruth.in
    

     

     

    ProductAction.jsx

     

     

    import { PRODUCT_LIST,PRODUCT_SEARCH } from "./Constant";
    
        export const productList =  () =>  {
    
        return {
            type: PRODUCT_LIST,
    
        }
    }
    
    export const productSearch = (query) => {
        return {
            type: PRODUCT_SEARCH,
            query,
        }
    }
    

     

     

    ProductSaga.jsx

     

     

    import { takeEvery, put } from 'redux-saga/effects';
    import {ADD_TO_CART, PRODUCT_LIST, PRODUCT_SEARCH, SET_PRODUCT_LIST} from './Constant';
    
    function* getProducts(){
     
         let data = yield fetch(`http://localhost:3000/products`);
         data = yield data.json();
         yield put({ type: SET_PRODUCT_LIST, data})
    
     
    }
     
    
    function* searchProduct(data) {
        let result = yield fetch(`http://localhost:3000/products?q=${data.query}`);
        result = yield result.json();
        console.log("product search is called", data);
        yield put({type: SET_PRODUCT_LIST, data:result})
    
        if (result.length === 0){
            console.log("not found");
        }
    }
    
    
    function* ProductSaga() {
     yield takeEvery(PRODUCT_LIST, getProducts)
     yield takeEvery(PRODUCT_SEARCH, searchProduct)
     
    }
    
    export default ProductSaga
    
    
    
    

     

     

     

    Search product with API in react redux saga

     

     

     


    # 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 

    # Add Redux Toolkit in react redux saga - CLICK HERE  

    # Configure MiddleWare saga - CLICK HERE   

    # Call API with Saga and Set Result in react redux saga - CLICK HERE    

    # Product list ui with API data in react redux saga - CLICK HERE    

    # Remove to Cart with ID react redux saga - CLICK HERE     

    # Add Routing and Make Cart Page - CLICK HERE   

    # Show Added To Cart Product with Price Calculation  - 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.