1

I have arrays of colors, with each color I have a gallery. I want to create and manage state for these galleries, so I can add/remove image for gallery easy.

I have code like this

var imgArr = new Array(colors.length)
for (var i = 0; i < colors.length; i++) {
    imgArr[i] = colors[i].imgs
    const [gallery[i], setGallery[i]] = React.useState()
    setGallery[i](imgArr[i])
}

but const [gallery[i], setGallery[i]] = React.useState() doesn't work.

How to resolve this issue?

5
  • None of these helped? Commented Feb 2, 2021 at 15:57
  • Does this answer your question? Calling setState in a loop only updates state 1 time Commented Feb 2, 2021 at 15:58
  • I need to create multiple state, not just call setState in the loop. Commented Feb 2, 2021 at 16:04
  • 1
    I believe the message in almost every single one of those many, many duplicate questions is this: Don't set state in a loop. Best of luck to you. Commented Feb 2, 2021 at 16:05
  • I got it, it's complicated for me, but I will try to use a state to manage them all. Commented Feb 4, 2021 at 2:48

1 Answer 1

1

Don't write this inside a loop:

const [gallery[i], setGallery[i]] = React.useState()

The syntax is wrong. What you could use is a galleries state like this:

const [galleries, setGalleries] = useState([]);

Then:

setGalleries(colors.map((color) => color.imgs));

Sandbox: https://codesandbox.io/s/stupefied-roentgen-xk9zc?file=/src/App.js:547-600. Hope this answers your question.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.