2

I am creating a dynamic object so this is the for loop:

for (let i = 1; i <= numOfPages; i++) {
    setDefinedPages(prevState => ({...prevState, i: {limit: partLimit, start: i }}))
}

The idea is to have the definedPages state object similar to this example:

1: {
  limit: 5,
  start: 1
},
2: {
  limit: 5,
  start: 2
}

But I can't accees i inside setState, the object writes literally i without any value. I have also tried:

setDefinedPages((prevState, i) => ({...prevState, i: {limit: partLimit, start: i }}))

but without any effect, I suppose this is expected behavior probably due to scope of the setState hook. Is there any workaround to catch current index?

Any help is appreciated, cheers

Update: Just before hitting Post question I have found that this is probably due to Closure inside the loop. I still can't get it to work though.

6
  • What about putting the loop inside the set state function? Commented Mar 14, 2021 at 1:45
  • 3
    Does this answer your question? How to use a variable for a key in a JavaScript object literal? Commented Mar 14, 2021 at 1:46
  • You could use a useRef and set the current value to i in each loop iteration, or just just save the object to a variable and set the state after the loop is finished. Commented Mar 14, 2021 at 1:47
  • Hei @y2bd thank you for the reference, it did solve one part of the issue and I used the answer below. Thank you for pointing it out, [ ] brackets are really quite helpful in these situations. Commented Mar 14, 2021 at 14:52
  • @evolutionxbox didn't think of that tbh, I may use it another time but I like the approach, thanks Commented Mar 14, 2021 at 14:54

1 Answer 1

1

try with something like this:

const ObjectArray = [];
const numOfPages = [1,2,3,4];
let x = 0;
numOfPages.map((el,i) => {
  ObjectArray.push( {limit: "5",start: i })
  x++;
})
console.log(ObjectArray);
console.log(ObjectArray[0])
console.log(ObjectArray[1])
...
setDefinedPages(ObjectArray);
Sign up to request clarification or add additional context in comments.

3 Comments

I’m not sure the OP wants to set defined pages to an array
Yep, would be good to see the initialization of the state. But the desired output will be achieved
@michael thanks for the reply. It does the desired output regarding i. Additionally I needed i: {limit: '5', start: i} so I achieved that with [i]: {limit: '5', start: i}. I combined multiple responses and it worked. Thanks again

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.