I am trying to build an app that requires a directory. Every time I update the component, it pushes the data into the array again creating multiple copies. I tried solving that by adding an !arry.includes, but that does not stop it for adding another occurrence of the data.
const Directory = () => {
const [searchResults, setSearchResults] = useState([]);
const [loading, setLoading] = useState(false);
const { currentUser } = useContext(AuthContext);
useEffect(() => {
setLoading(true);
const data = async () => {
const q = query(collection(db, "users"), where("type", "==", "doctor"));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
const data = doc.data();
if (!searchResults.includes(data)) {
searchResults.push(data);
}
});
setLoading(false);
};
data();
},[]);
console.log(searchResults);
2
Answers
I found an easier way!
It appears that you are trying to compare objects here which doesn’t work with the array.includes() method.
In javascript
You would need to search for something more specific or try Comparing Objects. Either way what your trying to do is tricky and you may need to explore lodash or something to solve it