DEV Community

Discussion on: How to cleanUp firestore data fetch on useEffect?

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