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.

fedjedmedjed
  • 415
  • 1
  • 6
  • 16
  • What about putting the loop inside the set state function? – evolutionxbox Mar 14 '21 at 01:45
  • 3
    Does this answer your question? [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal) – y2bd Mar 14 '21 at 01: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. – WebbH Mar 14 '21 at 01: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. – fedjedmedjed Mar 14 '21 at 14:52
  • @evolutionxbox didn't think of that tbh, I may use it another time but I like the approach, thanks – fedjedmedjed Mar 14 '21 at 14:54
  • @WebbH ```useRef``` got me out of several issues before but I didn't quite manage to comprehend it completely so it would be 'last thing to try' among these answers. Nevertheless thanks – fedjedmedjed Mar 14 '21 at 14:56

1 Answers1

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);
michael
  • 26
  • 3
  • I’m not sure the OP wants to set defined pages to an array – evolutionxbox Mar 14 '21 at 02:04
  • Yep, would be good to see the initialization of the state. But the desired output will be achieved – michael Mar 14 '21 at 02:20
  • @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 – fedjedmedjed Mar 14 '21 at 14:52