Is there a way to transfer multiple functions using a single context?

Having created individual contexts for my functions, I now seek to optimize them by consolidating all functions into a single context provider. The three functions that handle cart options are:

  1. handleAddProduct
  2. handleRemoveProduct
  3. handleCartClearance

In addition to combining the functions under one context provider, I am also looking to optimize their performance as they currently take a long time to execute.

import './App.css';
import data from './component/back/Data/data'
import Header from './component/front/Header/Header';
import { BrowserRouter as Router } from 'react-router-dom'
import Routiis from '. / component / front /Routiis/Routiis'
import { createContext, useState } from 'react';

const AddProduct = createContext();
const RemoveProduct = createContext();
const EmptyCart = createContext();

const App = () => {
  const { productItems } = data;
  const [cartItems, setCartItems] = useState([]);

  // function for adding the product...............................................................................................

  const handleAddProduct = (product) => {
    const ProductExist = cartItems.find((item) => item.id === product.id)
    if (ProductExist) {
      setCartItems
        (cartItems.map((item) => item.id === product.id ?
          {...ProductExist, quantity: ProductExist.quantity + 1 } : item))
    }
    else {
      setCartItems([...cartItems, {...product, quantity: 1 }])
    }

  }

  // function for removing the product..............................................................................................

  const handleRemoveProduct = (product) => {
    const ProductExist = cartItems.find((item) => item.id === product.id)
    if (ProductExist.quantity === 1) {
      setCartItems(cartItems.filter((item) => item.id ! == product.id))
    }
    else {
      setCartItems(
        cartItems.map((item) => item.id === product.id ?{...ProductExist, quantity: ProductExist.quantity - 1}: item,)
      )
    }
  }

  //function for clearing the cart...................................................................................................

  const handleCartClearance = ()=>{
    setCartItems([]);
  }

  return (
    <>
      <div className='site-bg'>

        <AddProduct.Provider value={handleAddProduct}>
          <RemoveProduct.Provider value={handleRemoveProduct}>
            <EmptyCart.Provider value={handleCartClearance}>
              <Router>
                <Header cartItems={cartItems} />
                <Routiis productItems={productItems} cartItems={cartItems}/>
              </Router>
            </EmptyCart.Provider>
          </RemoveProduct.Provider>
        </AddProduct.Provider>
      </div>
    </>
  );
}

export default App;
export { AddProduct, RemoveProduct, EmptyCart}

Answer №1

The Provider component allows for the passing of a value prop to descendant components within its hierarchy. This object can contain function properties, simplifying consumption of the Product.

This should address your inquiry.

 <>
      <div className="site-bg">
        <Product.Provider
          value={{
            handleAddProduct: handleAddProduct,
            handleRemoveProduct: handleRemoveProduct,
            handleCartClearance: handleCartClearance,
          }}
        >

          <Router>
            <Header cartItems={cartItems} />
            <Routiis productItems={productItems} cartItems={cartItems} />
          </Router>

        </Product.Provider>
      </div>
    </>

Refer to the official React context documentation for more information and guidance.

Answer №2

If you want to make things simpler, instead of passing a single parameter as a value, pass it as an object like this:

<AddProduct.Provider value={{handleAddProduct:handleAddProduct, handleRemoveProduct:handleRemoveProduct}}>
</AddProduct.Provider>

Then in your code, simply access these functions like this:

const { handleRemoveProduct, handleAddProduct } = useContext(AddProduct);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenges with Socket.io in Kubernetes Deployment

I am currently developing a collaborative whiteboard application that utilizes socket.io to communicate with MongoDB. The backend-service, which is in a separate pod from the whiteboard pod, handles all communication. For example: whiteboard app -> bac ...

Sign in using username or email address

Previously, I was unsure of how to allow users to log in using either their username or email. However, after some exploration, I have successfully implemented the feature where users can now log in using their email. auth.js: //LOGIN router.post("/login" ...

Implementing auto-complete functionality for a text box in an MVC application using jQuery

After incorporating code for auto completion in a text box using AJAX results, the following code was utilized: HTML: <div class="form-group col-xs-15"> <input type="text" class="form-control" id="tableOneTextBox" placeholder="Value" > ...

Vanishing Items - Three.js CanvasRenderer

I'm in a bit of a pickle here. I can't figure out why my objects are disappearing when using the canvas renderer. Strangely enough, everything works fine with the webGL renderer. Unfortunately, I need to make sure this displays properly on mobile ...

Steer clear of retrieving all the elements from the HTML DOM at once

Scenario I am working on a HTML5+CSS+JS slideshow project that needs to be synchronized across 50 clients in a local area network using a single wireless router. Challenge Due to the heavy content, particularly images, of the slides, I intend to dynamic ...

Scrolling with JQuery between a webpage's header and footer

I'm having trouble keeping a div at the top of my page, but I want it to stop scrolling before reaching another div. <div class="my-top"><p>This is the top</p></div> <div class="big-one"> <div class="mini1 ...

What is the process for conducting JUnit tests using just a single graphical user interface?

After writing some JUnit test cases for Winium, which is similar to Selenium but for Calculator, I encountered an issue where a new calculator.exe is started with every test. What I want is to use the same calculator.exe for all tests while still keeping ...

EmberJS add item to an object through pushObject

I'm currently working on setting up a property within an object that will also be an object itself. For example, let's say I have a property named 'cities' and I want to assign populations to different cities within this object. cities ...

What's the point of using defer() in Node.js Q promises when you have the option to simply use this

I had a plan in mind: somePromiseFunc(value1) .then(function(value2, callback) { // insert the next then() into this function: funcWithCallback(callback); }) .then(function(dronesYouAreLookingFor){ // Let's celebrate }) .done(); Unfortun ...

Ways to address the problem of returning assignments

I encountered an issue while working on my code Error message: Arrow function should not return assignment no-return-assign The problematic code snippet is as follows: await DB.Place.find( match, // key to filter (err, doc) => (listOfObje ...

The functionality of the web application is not supported in Multi-Device-Hybrid-Apps format

I am encountering an issue with my app that functions perfectly as a typical web app, but fails to work properly when converted into a Multi-Device-Hybrid-App format. The problematic sections are indicated in a screenshot of the app. Below is my complete c ...

I am looking to have the first option in the dropdown menu appear as a placeholder text

In my form, I have two phone number fields - one for mobile phone and the other for home phone. I need to make only one of them mandatory. Can someone please advise me on how to accomplish this? ...

What is the method for importing jQuery from a local source?

My experience with CDNs has been seamless, but I've run into some issues when trying to use jquery/jquery mobile locally. It seems that certain classes work intermittently, while others don't work at all. The versions I am using are: jQuery - ...

What is the best way to delete a specific item class from a child element using CSS and React?

I am looking for a solution to remove a class or its effect if the parent element does not have a "thanks" element, or have the option to refer to its reference to enable selection. I have been searching online without success and need some suggestions. Th ...

React encountered an unexpected end of JSON input while streaming JSON data

Currently, I am facing a challenge with streaming a large amount of data from a NodeJS server that retrieves the data from Mongo and forwards it to React. Due to the substantial volume of data involved, my approach has been to stream it directly from the s ...

Understanding the interplay between transient and final in Java Serialization

Exploring the nuances of the transient and final keywords led me to an interesting discovery - contrary to what I had read, it seems that using the transient keyword with the final keyword is actually possible. This realization left me somewhat perplexed. ...

Div expanding beyond intended size when media reaches maximum 468 pixels

When zoomimg is set to width: 145px; height: 145px; it ends up pushing the text that should be inside its parent element out of the parent. If you want to see the Zoomimg ProjectKort divs, check out the code below: .projectkort{ margin: 10px 0px 10px 0 ...

What is the best way to retrieve the values of "qty" and "price" and access them within the item [array] without knowing the IDs?

I am currently working on a shopping cart project, specifically on the "previous orders" page to display order details. My goal is to output this information in an (.ejs) file. The data structure includes nested objects, and within one object, propertie ...

Using the request.getParameter method for casting in Java

I'm really struggling to understand why I'm being instructed to cast the object returned by getParameter to a string in the code below. When I try to assign it to the String variable "user," I encounter the error 'Type mismatch: cannot conve ...

Error encountered during Nuxt build: Syntax error on Line 1 of the SCSS component file

I'm currently working on a project in node 18.7.0 that utilizes nuxt 2.15.8. Within my Vue component, I have the following SCSS code: <style lang="scss"> .Accordion { --Accordion__margin-top: 2.5rem; &__items { margin ...