Use index from for loop inside setState

Viewed 60

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.

1 Answers

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);
Related