DEV Community

Olimpio
Olimpio

Posted on

How to cleanUp firestore data fetch on useEffect?

Hello guys... I need your help... When (quickly) navigating on my react website... I get this error on the console. I heard I need to use the cleanUp function in order to correct this error. But I am using firebase firestore to fetch the data so I dont know how to solve this error...
Here is the error on the console
image

Here is the code of the useEffect hook I am using...

useEffect(() => {
    const fetchDb = db.collection('posts');

    fetchDb.get()
      .then(response => {
        const fetchedPosts = [];
        response.docs.forEach(post => {
          const fetchedPost = {
            id: post.id,
            ...post.data()
          };
          fetchedPosts.push(fetchedPost);
        });
        setPosts(fetchedPosts);
        setIsLoading(false);
      })
      .catch(error => {
        error = 'Houve um erro'
        setError(error);
      });
  }, []);
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
ashirbadgudu profile image
Ashirbad Panigrahi

Checkout This Code

// Create Ref
  const isMounted = useRef(false);
// Create Your Required States
  const [posts, setPosts] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
// Create a function for fetching your data
  const fetchData = () => {
    const fetchDb = db.collection('posts');
    fetchDb
      .get()
      .then(response => {
        const fetchedPosts = [];
        response.docs.forEach(post => {
          const fetchedPost = {
            id: post.id,
            ...post.data(),
          };
          fetchedPosts.push(fetchedPost);
        });
        // check ref before updating state 
        if (isMounted.current) {
          setPosts(fetchedPosts);
          setIsLoading(false);
        }
      })
      .catch(error => {
        // check ref before updating state 
        isMounted.current && setError(error);
      });
  };
  useEffect(() => {
    isMounted.current = true;
    fetchData();
    // this is run when component unmount
    return () => (isMounted.current = false);
  }, []);
Enter fullscreen mode Exit fullscreen mode