DEV Community

Olimpio
Olimpio

Posted on

4 1

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay