skip to Main Content

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


  1. Chosen as BEST ANSWER

    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();
        };
      }, []);
    

  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search