Home > Net >  How to pass multiple data in state?
How to pass multiple data in state?

Time:12-06

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.

CodePudding user response:

you need to set data like this

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

CodePudding user response:

You need to update the data this way:

const handleaddnowFunc = data => {
   setAddNow(prevState => ([...prevState, data]));
};

CodePudding user response:

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?

  • Related