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

How to add data in an array inside object reactjs

I am building an react app and want to save multiple photos to firestore to do that i want to take their url in imageurl: [] an array to save them in firestore.

      const [data, setData] = useState({

      name: "",
      phone: "",
      location: "",
      imageurl:[],

   })

here every data is saving and working fine name,phone,location but the problem is with array value imageurl[] they are not saving

i m saving urls like

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

            setData((prev)=> {

              return {

                ...prev, [data.imageurl] : [...data.imageurl , url]
              }
            })
           })

it is not working.

i am new to react please guide me how can i solve this problem. thank you

>Solution :

In the setData when creating the return object you have put the value as key, when you set the key as [data.imageurl]. also don’t use the data variable inside setData, use the prev variable supplied by the function

try this code

setData((prev) => {
   return {
      ...prev,
      imageurl: [...prev.imageurl, url],
  };
});
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