I have an PostImagesList component that updates when an image is removed. I also send the removed image id to the parent for deletion if the post update is ultimately committed.
I'm trying to understand why a prop function (onRemoveImage) kills the setImages useState hook, unless I remove the same image twice(?) Presently in the parent I am only logging the id sent from the child so nothing is changing with the data.
// <PostImagesList />
const handleRemoveImage = (e, idx, imageId) => {
e.stopPropagation();
let newFilesArr = [...images];
newFilesArr.splice(idx, 1);
setImages(newFilesArr);
onRemoveImage(imageId); // If I comment this out, the setImages updates correctly
};
images is initially set in PostImagesList in a useEffect hook:
useEffect(() => {
setImages(
imagesByPostId?.edges
? imagesByPostId?.edges
.filter(Boolean)
.map((edge) => edge.node)
.filter(Boolean)
: [],
);
};
CodePudding user response:
I can't see where you declared setImages but if you want to set the initial state you can do like:
const [state, setState] = React.useState(whatever)
If you want to set it depending on complex conditions, then you can use React.useReducer instead of React.useState or define initial state like:
const [state, setState] = React.useState(() => {
if (itsCool) return "cool";
else return "not cool";
});
If you need to use that useEffect hook and you want to set something at the initial render then you need to pass an empty dependency Array, else you can run into "Maximum update depth exceeded" because setState will call repeatedly. So do it like:
useEffect(() => {
setImages(
imagesByPostId?.edges
? imagesByPostId?.edges
.filter(Boolean)
.map((edge) => edge.node)
.filter(Boolean)
: [],
);
}, []); // here is the empty dependency array
