Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

return false even though data is present in the array

I make a query that responds with users’ data.

This user is obtained from api response.

users = [
       {
        "email": "test123@gmail.com",
        "name": "test user",
        "uid": "1612848114665355196015101548881161"
    },
    {
        "email": "test123@gmail.com",
        "name": "test user",
        "uid": "1612848114665355196015101548881161"
    }
]

I need to find if a user (test123@gmail.com) exists in the array, and if not create a user.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I looped through each of the arrays checking for the user exists, if yes return true or else false.

But Even though the user exists in the array, it gives false.

Code:

  const checkIfUserThere = async () => {
    let newUser = "test123@gmail.com";
    await users.map((user: any) => {
      if (user.email === newUser) {
        return true;
      }
    });
    return false;
  };

  useEffect(() => {
    (async () => {
      const userExists = await checkIfUserThere();
      console.log(userExists);
      if(userExists === false){
         createuserapi("....") //create user api is called
      }

    })();
  }, [users]);

Above returns false

>Solution :

It will work as you want

 const checkIfUserThere = () => {
   let newUser = "test123@gmail.com";
    for (const data of users) {
     if (data.email === newUser) {
       return true;
        }
    }

     return false;
  };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading