Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
how do I pass all these function using only one context

I have these all context created, but now I want to make it optimized. How do I pass all the created functions using only one context provider. I have three functions to handle the cart options

  1. handleAddProduct
  2. handleRemoveProduct
  3. handleCartClearance

I've created context for each function but now I want all the functions to be wraped in a single context provider.

and also need some optimizations for my all three functions because they are taking long to perform the action.

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 }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider. you could provide it with an object that carries the properties of the functions. and hence you only need to consume the Product

this answers your question

 <>
      <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>
    </>

Take a quick look at the official React context docs, it might be helpful.

about 4 years ago · Juan Pablo Isaza Relatório

0

Actually it is very easy. instead of passing one parameter as value pass it as object as below

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

like this and in your code where you want to use these function just do like this

const { handleRemoveProduct,handleAddProduct } = useContext(AddProduct);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda