I am trying to add all added images to a state, so I use spread operator.
I am not sure what I am doing wrong, since it just overwrites the previous value.
It seems that I am missing something.
useEffect(() => {
if (addButton.current) {
if (scene) {
setImages([...allImages, newImg]); // <-- Here
}
});
}
}, [addButton]);
2
Answers
You need an
addImage(newImage)
function declared inS.js
and you should pass that toM.js
instead ofsetImages
.Now in
S.js
have the following:In
M.js
you have:Since
S
holds the state of the images, you need to essentially send a signal fromM
toS
; to getS
to update and cascade changes back down toM
.The main takeaway here is that you should be using the function version of
setState
to get the current list of images, rather than the actual reference toallImages
. If you use this inside of an effect, you will have an infinite loop.A quick search for "useState pitfalls" on Google will list a few helpful blog posts that will help you avoid these issues.
To answer your question in short. Use functional state update to set the state. Like this:
Let me go through some lines of your code.
I see that you are forwarding refs to child component
M
fromS
. In that case, you need to follow the react way of forwarding ref. Currently, react is logging error for you to identify this issue in the console. Right way would be something like this for line number 8 – 15.React provides this reason to do so:
This happens because by default React does not let a component access the DOM nodes of other components. Not even for its own children! This is intentional. Refs are an escape hatch that should be used sparingly. Manually manipulating another component’s DOM nodes makes your code even more fragile.
By default React does not let a component access the DOM nodes of other componentsLikewise in your useEffect hook from line 27 to 62, there are some refactoring to do. Let me paste the code here and explain some changes in the comment section:
That’s it. That would do it.