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
CodePudding user response:
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);
};