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.
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;
};