codebooker icon indicating copy to clipboard operation
codebooker copied to clipboard

Title: Infinite Fetching Loop and Memory Leak in fetchBooksFromDB Function

Open dev-george-nikolaidis opened this issue 1 year ago • 2 comments

Describe the bug The fetchBooksFromDB function triggers an infinite loop of data fetching when used in conjunction with useEffect, leading to significant performance degradation and a memory leak.

Expected Behavior

fetchBooksFromDB should fetch the data once and stop, without causing an infinite loop or memory leaks.

Actual Behavior

The function continuously fetches data without stopping, causing browser performance issues and memory leaks.

Additional Information

memoryLeak

dev-george-nikolaidis avatar Mar 24 '24 14:03 dev-george-nikolaidis

@dev-george-nikolaidis

This is also due to the fact we were also trying to handle a case for using the data.json file for if the database/collection in MongoDB were ever to 1) not exist 2)database be down for whatever reason 3) server be down for whatever reason.

After thinking about this from the previous issues we have had with this, I also think we could have:

const fetchBooksFromDB = async () => {
  try {
    setLoading(true);

    // Attempt to fetch data from the database
    const response = await axios.get('http://localhost:3001/api/books/getall');
    const books = response.data;

    // Database success: Use books from the database
    if (books.length > 0) {
      setMyRows([...books]);
      return; // Exit the function if database fetch is successful
    }

    // Handle database failure: Try fetching from data.json
    console.warn('Database fetch failed. Attempting to fetch from data.json');
    const fileData = await fetch('data.json');
    const fileBooks = await fileData.json();

    // Data.json success: Use books from data.json and potentially update the database
    if (fileBooks.length > 0) {
      setMyRows([...fileBooks]);
      // Optionally call a function to add the fetched books to the database (addBooksToDB)
    } else {
      // Both database and data.json failed: Handle fallback scenario (e.g., display error message)
      console.error('Both database and data.json fetch failed.');
    }
  } catch (error) {
    // Handle errors related to both database and data.json fetching
    console.error('Error fetching books:', error);
  } finally {
    setLoading(false);
  }
};

in the case we have now, it really needs to have the dependency array or it will grow huge.

gbowne1 avatar Mar 26 '24 05:03 gbowne1

This still has not been solved yet and it really decreses the project speed by a lot by it continually fetching the library.

gbowne1 avatar Sep 12 '24 20:09 gbowne1