0

I want to update a shopping cart when I click on a Product. But I don't know, how to call the function in another component.

This is, where the function is written and the state of the cart is hold.

    export const Cart = () => {
    const [userId, setUserId] = useState(7);
    const [cart, setCart] = useState([]);
    const [outfitName, setOutfitName] = useState("");
    
    const sendOutfit = () => {
        axios.post(`{url}/postOutfit`, {
            userId,
            outfitName,
            cart,
        });
    };
    
    function addToCart(id) {
        cart.push(id);
        setCart(cart);
    }
...
}

Here I want to call the addToCart function.

import { Cart } from "../../sites/Cart/Cart";
...

 <div className="product-name">
                    <button
                        className="button is-small is-outlined is-primary"
                        onClick={() =>
                            Cart.addToCart(product.id) & changeButtonText
                        }
                    >
                        {buttonText}
                    </button>
                </div>

When I try to execute this, I get the following error message: enter image description here

Do you have any suggestion for me?

Thank you very much!

3
  • It doesn't work like that, you have to pass down the addToCart function as a prop. (The Cart you're importing is the function itself, not the rendered instance in your running app. Even if it were, Cart.addToCart is undefined because addToCart is a function defined inside the Cart function, not a property of it) Commented Feb 10, 2022 at 13:07
  • How are these two components related? Where does one of them render the other one? Commented Feb 10, 2022 at 13:08
  • 1
    Please read How to Ask, where it notes, "DO NOT post images of code, data, error messages, etc. - copy or type the text into the question." Commented Feb 10, 2022 at 13:15

2 Answers 2

1

You can not do this like that. Below I wrote simple example and here is nice article I suggest to read it first: Components and Props

const AddToCartButton = ({ setCart }) => {
  return (
    <button
      onClick={() => {
        setCart("item");
      }}
    ></button>
  );
};
const Cart = () => {
  const [cart, setCart] = React.useState([]);
  return <AddToCartButton setCart={setCart} />;
};
Sign up to request clarification or add additional context in comments.

Comments

0

Methods in React return JSX values ​​and in this way it is not correct to export a method, if you want to export the method of addToCart to a another component you need to send this method as propeties or using state management for example as follows:

    export const Cart = () => {
    const [userId, setUserId] = useState(7);
    const [cart, setCart] = useState([]);
    const [outfitName, setOutfitName] = useState("");
    
    const sendOutfit = () => {
        axios.post(`{url}/postOutfit`, {
            userId,
            outfitName,
            cart,
        });
    };
    
    function addToCart(id) {
        cart.push(id);
        setCart(cart);
    }

   return <AnotherComponent addCartFunc={addToCart} />

}

Then you can use this method in the host component as follows:

export const Cart = ({addCartFunc}) => {
   return (
        <div className="product-name">
            <button
                className="button is-small is-outlined is-primary"
                onClick={() =>
                    addCartFunc(product.id) & changeButtonText
                }
            >
                {buttonText}
            </button>
        </div>
   )
}

3 Comments

Thank you for your suggestions. My Problem is, that the Cart is not a parent component of the ProductCards. They are created out of o List of Products. Is ist useful to have the state in a react.context?
In this case you will use state manegemt to pass the method, for example useConext Hook Would you like me to attach an explanation of how to use it?
Or is it easer to set a cookie or sessionStorage and after the products are buyed, this cookie or sessionStorage-Item will be deleted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.