gbowne1 / codebooker

This is a book recommendation app created with React 18.2 and MUI for coders/programmers looking for reccomendations to books on programming/coding to read
MIT License
31 stars 57 forks source link

Title: Infinite Fetching Loop and Memory Leak in fetchBooksFromDB Function #220

Closed dev-george-nikolaidis closed 1 month ago

dev-george-nikolaidis commented 8 months ago

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

gbowne1 commented 8 months ago

@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 commented 2 months ago

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