Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pushing objects in an array only returns last object pushed in react

I Know this question to be duplicated, but none of the other answers worked for me…
I am trying to push objects to my array using the onChnage method. But every time my array returns the last value, not the full value. I tried so many times to fix this issue. But I can’t.

function addVariantSection(data) {
    const handleChecked = (id) => (e) => {
      const tempData1=[];
      const { checkedID } = e.target;
      const vID = e.currentTarget.id.split('-', 1);
      tempData1.push({ productId:itemID, variantId:vID})
      setChecked((values) => ({ ...values, [id]: checkedID, }));
      setVariant([...tempData1]); // variant always give the last value.
    };
    return (
      <Grid key={data._id} container spacing={10}>
        <Grid item xs={12} style={{ justifyContent: 'space-between', display: 'flex' }}>
          <div>{`${data.variant1}-${data.variant2}`}</div>
          {/* eslint-disable-next-line no-useless-concat */}
          <Checkbox id={`${data._id}-` + `checkData`} color="primary" checked={checked[data._id]} onChange={handleChecked(data._id)} />
        </Grid>
      </Grid>
    );
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are overwriting setVariant with the array – tempData1. So you need to preserve the previous value of setVariant to get the complete array you are expecting.

So do this instead

setVariant((prev) => ([...prev, ...tempData1]));

Your function will look like this:

const handleChecked = (id) => (e) => {
    const tempData1=[];
    const { checkedID } = e.target;
    const vID = e.currentTarget.id.split('-', 1);
    tempData1.push({ productId:itemID, variantId:vID})
    setChecked((values) => ({ ...values, [id]: checkedID, }));
    setVariant((prev) => ([...prev, ...tempData1]));
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading