0

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);
Jacqueline
  • 21
  • 7

2 Answers2

0

It appears that you are trying to compare objects here which doesn't work with the array.includes() method.

In javascript

const user1 = {name : "nerd", org: "dev"};
const user2 = {name : "nerd", org: "dev"};
user1 == user2; // is false

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

schmell
  • 50
  • 8
0

I found an easier way!

 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();
        const notInArray = searchResults.some(u => u.uid === data.uid);
        console.log(notInArray);
        if (notInArray === false) {
          searchResults.push(data)
        }
      });
      setLoading(false);
    };
    return () => {
      data();
    };
  }, []);
Jacqueline
  • 21
  • 7