2

I have warning from ReactJS

Function declared in a loop contains unsafe references to variable(s) 'level'

How to fix my loop? I don't know how to send ver level and change it in my infinity loop.

const catTree = [{"id": "963",
    "level": 1},
  {"id": "998",
    "level": 2},
  {"id": "1636",
    "level": 2}];
let cats = [];
let level = 1;
let catsCand = [];
for (; cats.length < 2;) {
  cats = catTree.filter((cat) => {
    return cat.level === level;
  });
  if (!catsCand.length) {
  // if all levels give less then 2 cats
    catsCand = cats;
  }
  level += 1;
  if (!cats.length) { // if level is not exists
    cats = catsCand;
    break;
  }
}

Thanks!

Answer: Just move level var to "for" loop.

let cats = [];
// показать корень
let catsCand = [];
for (let level=1; cats.length < 2; level++) {
  cats = catTree.filter((cat) => {
    return cat.level === level;
  });
  if (!catsCand.length) {
  // если все уровни дадут меньше 2 категорий
    catsCand = cats;
  }
  if (!cats.length) { // если пошел несуществующий уровень
    cats = catsCand;
    break;
  }
}
user3713526
  • 435
  • 7
  • 16
  • 1
    Does this answer your question? [Debugging: ESLint Warning "Function declared in a loop contains unsafe references to variable(s)...no-loop-func"](https://stackoverflow.com/questions/58816244/debugging-eslint-warning-function-declared-in-a-loop-contains-unsafe-reference) – Cameron Little Apr 01 '20 at 17:58
  • 2
    Just so you know, that error message is coming from eslint. The documentation for the rule can be found at https://eslint.org/docs/rules/no-loop-func – Cameron Little Apr 01 '20 at 17:58

0 Answers0