How to pass multiple data in state?

How to pass multiple data in state?

Problem Description:

I need the output like this

{
        id: 1,
        image: "/assets/images/3d-rendering.png",
        name: "Screen",
        mrp: 950.8,
        sale_price: 950,
      },
      {
        id: 2,
        image: "/assets/images/charger.png",
        name: "Screen2",
        mrp: 950.1,
        sale_price: 951,
      },

I declare the addnow in array.

const [addnow, setAddnow] = useState([]);

when i click Add Now button the hole data send to the state value.

 {repairservicedata.map((data, index) => (
                      <div className={Styles.repaircard} key={index}>
                        <div className={Styles.repaircardins}>
                          <img src={data.image} alt="" />
                          <div>
                            <h6>{data.name}</h6>
                            <span className={Styles.pricestrkoutcard}>
                              {data.mrp}
                            </span>
                          </div>
                        </div>
                        <div className={Styles.priceblock}>
                          <h5 className={Styles.price}> {data.sale_price}</h5>
                          <Button
                            className={Styles.addnwbtn}
                            onClick={() => handleaddnowFunc(data)}
                          >
                            Add Now
                          </Button>
                        </div>
                      </div>
                    ))}

This is the function i added. but it’s not getting the old data and add the new data. it shows addnow is not iterable

const handleaddnowFunc = (data) => {
    if (addnow.length === 0) {
      setAddnow(data);
    } else {
      setAddnow([...addnow, { data }]);
    }
  };

I need to pass multiple json data in single state value.

Solution – 1

you need to set data like this

setAddnow([...addnow.map(d => ({...d})), { ...data }]);

Solution – 2

What type of addnow?

there are two reasons for this

  1. it is a strict type state array that’s why it is not iterable;
    therefore, you must clone this array and then iterable this addnow array.

  2. you have declared another type like {}.

got it?

Solution – 3

You need to update the data this way:

const handleaddnowFunc = data => {
   setAddNow(prevState => ([...prevState, data]));
};
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject