I wanted to perform a query where the user enters the first and last name. And in firestore, this will search for the first and last name. The problem here is that as soon as I finish typing in the first and last name, it does not display anything in the console.
However, if I'll go back and update something in the code and save it, so it kinda loads the component again, that is the only time that I can see the result of the query.
useEffect(() => {
let isMounted = true;
const getUsers = async () => {
const ordersRef = collection(db, "users");
const q = query(
ordersRef,
where("firstName", "==", firstName),
where("lastName", "==", lastName)
);
const querySnapshot = await getDocs(q);
const arr = [];
querySnapshot.forEach((doc) => {
arr.push({
...doc.data(),
id: doc.id,
});
});
if (isMounted) {
console.log(arr, "arr");
setUsers(arr);
}
};
getUsers().catch((err) => {
if (!isMounted) return;
console.error("failed to fetch data", err);
});
return () => {
isMounted = false;
};
}, []);
Input field: This is the same with the 'lastName'
<TextField
variant="outlined"
label="First Name"
fullWidth
required
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>
Your useEffect() is set to only run its callback function the very first time the component renders (i.e. the second argument you pass to useEffect() is an empty array [ ]).
If you want the useEffect to run its callback under some other circumstances (e.g. if the value of firstName changes), then you need to list it in the dependency list (i.e. set the second argument to [firstName]).
Note however that this means that the callback will be called whenever firstName changes. This might not be exactly the behaviour you want....each time you type a letter it would run the callback.
But first, get the above working. Once you understand how that works, you can then look to tackle a way to "debounce" the callback (i.e. call it less frequently...after some type of delay in updating firstName).
And you likely want the same when it comes to a change to lastName.