Home > Mobile >  How to reset values of a state in React JS
How to reset values of a state in React JS

Time:03-03

I am learning React JS. I am doing a demo project where I have a discard button to reset the values of state. I have implemented the function and it seems ok to me but not working.

I am passing handleResetCart function through <Cart /> component.

App.js

function App() {
  const [totalPrice, setTotalPrice] = useState([]);
  const [totalItems, setTotalItems] = useState([]);

  const handleCart = course => {
    const newItems = [...totalItems, course];
    setTotalItems(newItems);
    const newPrice = [...totalPrice, course.price];
    setTotalPrice(newPrice);
  };

  const handleResetCart = () => {
    setTotalPrice([]);
    setTotalItems([]);
  }

  return (
    <div className="app">
      <Navbar />
      <div className="container">
        <div className="row">
          <div className="courses col-9">
            {data.map(course => (
              <Course key={course.id} course={course} handleCart={handleCart} />
            ))}
          </div>
          <div className="cart col-3">
            <Cart
              totalPrice={totalPrice}
              totalItems={totalItems}
              handleResetCart={handleResetCart}
            />
          </div>
        </div>
      </div>
    </div>
  );
}

I am calling the handleCarReset function through the Discard button.

Cart.jsx

import React from 'react';

const Cart = props => {
  const { totalPrice } = props;
  const { totalItems } = props;
  const price = totalPrice.reduce((t1, t2) => t1   t2, 0).toFixed(2);

  return (
    <div className="card">
      <div className="card-body">
        <h5 className="card-title text-center">
          CART <i className="bi bi-cart-plus-fill"></i>
        </h5>
        <hr />
        <p>Courses Added: {totalItems.length}</p>
        <p>Total Price: ${price}</p>
        <hr />
        <div className="d-flex justify-content-between">
          <button
            className="btn btn-outline-danger btn-sm"
            onClick={() => props.handleResetCart}>
            Discard
          </button>
          <button className="btn btn-outline-success btn-sm">Buy Now</button>
        </div>
      </div>
    </div>
  );
};

export default Cart;

Where is the problem? How to solve this?

CodePudding user response:

Seems like in your cart component, you are returning a reference of handleResetCard function when onClick event happens. You need to invoke handleResetCard function instead.

Fix button onClick like below

// cart.jsx

<button
  className="btn btn-outline-danger btn-sm"
  onClick={() => props.handleResetCart()}>
  Discard
</button>

or more concisely without creating an arrow funciton

// cart.jsx

<button
  className="btn btn-outline-danger btn-sm"
  onClick={props.handleResetCart}>
  Discard
</button>

CodePudding user response:

You can use it

 onClick={() => props.handleResetCart()}>
  • Related