How to access callback function value inside a normal function in react

Viewed 131

this is the react code and i want to access the cart value and totaPrice value inside the return

function A() {
    const Cart = () => {
        const [cart, setCart] = useContext(CartContext);
        const totalPrice = cart.reduce((acc, curr) => acc + curr.add, 0);
    };
    return <div>i want to use {totalPrice} value here how can I?</div>;
}

export default A;
1 Answers

React hooks(useContext) should be defined in the top level of the function component.

You can declare a function to return the total of the cart like below.

function A() {
    const [cart, setCart] = useContext(CartContext);

    const getCartTotal = () => cart.reduce((acc, curr) => acc + curr.add, 0);

    return <div>i want to use {getCartTotal()} value here how can I?</div>;
}

export default A;
Related