Sohaib
Sohaib

Reputation: 29

React js Function declared in a loop contains unsafe references to variable(s) 'allowed'

Getting this warning but code is working fine Function declared in a loop contains unsafe references to variable(s) 'allowed' If i create a hook state for allowed then there is no warning but the code doesn't work. How can i declare a variable without using a useState. Code is attached.

const checkAllowed = async () => {
    let allowed = 1;
    await axios
      .get("http://localhost:4000/api/courses/eachstage/" + props.data.CourseID)
      .then(async (res) => {
        for (let i = 0; i < res.data.length; i++) {
          await axios
            .get("http://localhost:4000/api/courses/allow/" + res.data[i].StID)
            .then(async (response) => {
              if (response.data === 0) {
                allowed = 0;
              }
            });
        }
      });
    return allowed;
  };

Upvotes: 0

Views: 4798

Answers (2)

Edward Sanchez
Edward Sanchez

Reputation: 29

I'm not sure you need to return but try this, a little more tidy and the scope works better

const checkAllowed = async () => {
    const { data } = await axios.get(`http://localhost:4000/api/courses/eachstage/${props.data.CourseID}`)
    const arrAllow = await Promise.all(data.map(async ({ StID }) => {
      return await axios.get(`http://localhost:4000/api/courses/allow/${StID}`)
    }))

    const allowFind = arrAllow.find((data) => data === 0)

    return !Boolean(allowFind) ? 1 : 0
  }

Upvotes: 0

rfestag
rfestag

Reputation: 2008

The warning is occurring because you are declaring allowed outside of a for loop, then modifying it within a function defined within the for loop). This is discouraged because it may not behave as you expect.

  1. You can declare the async response handler outside of the loop, and pass it in as a parameter instead of declaring it inline.
  2. You can use reduce over the results instead of a for loop.

You may also want to not await within the loop, and instead return an array of promises that you await a Promise.all. That would let you do more of the requests in parallel

More details can be seen here: https://eslint.org/docs/rules/no-loop-func

Upvotes: 2

Related Questions