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

Replace the first element in an array

I want to replace the first element in an array. When I try the following, I get the error below. So I just want to always renew the first element in the array with another one

const changeMainpIC = (e) => {
 const pic = e.target.files[0];
 const copy = pics;
 copy[0] = URL.createObjectURL(pic);
 setPics([copy]);
};

blob:http://localhost:3000/65ea67c6-4afb-473e-b36c-f22799082e69,blob:http://localhost:3000/7cb0ad60-316c-4896-8669-xxxx:1 GET blob:http://localhost:3000/65ea67c6-4afb-473e-b36c-xxx,blob:http://localhost:3000/7cb0ad60-316c-4896-8669-xxxnet::ERR_FILE_NOT_FOUND

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

>Solution :

I am assuming that you have a state set using the setState() hook. I believe the below should work:

const [pics, setPics] = useState([])

const changeMainpIC = (e) => {
 const pic = e.target.files[0];
 const copy = [...pics]; // using the spread operator to create a copy of the pics array
 copy[0] = URL.createObjectURL(pic); //no need to put copy in square brackets because it is already an array
 setPics(copy);
};
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