Encountering an endless loop while attempting to retrieve data from Firebase in Next.js through the use of useEffect

Currently, I am in the process of setting up a video section for a project using NextJS. The videos are stored in firebase storage.

I have implemented a dynamic route that retrieves all videos from a specific reference within the bucket. For instance, if my bucket is named somebucket and it contains a folder called training with categories (category-1, category-2, category-3), each category will serve as a dynamic route like localhost:3000/training/category-1. So far, everything is running smoothly.

The file responsible for the dynamic route is named [id].js

// ReactJS
import { useState, useEffect } from "react";

// NextJS
import { useRouter } from "next/router";

// Hooks
import { withProtected } from "../../../hook/route";

// Components
import DashboardLayout from "../../../layouts/Dashboard";

// Firebase
import { getMetadata, listAll, ref } from "firebase/storage";
import { storage } from "../../../config/firebase";

// Utils
import capitalize from "../../../utils/capitalize";
import { PlayIcon } from "@heroicons/react/outline";

function Video() {
  // States
  const [videos, setVideos] = useState([]);

  // Routing
  const router = useRouter();
  const { id } = router.query;

  // Reference
  const reference = ref(storage, `training/${id}`);

  useEffect(() => {
    function exec() {
      listAll(reference).then((snapshot) => {
        const videos = [];
        snapshot.items.forEach((video) => {
          videos.push(video);
        });

        setVideos(videos);
      });
    }

    exec();
  }, [reference, videos]);

  return (
    <DashboardLayout>
      <h2>{capitalize(reference.name)}</h2>
      <section>
        <video controls controlsList="nodownload">
          <source
            src="https://example.com"
            type="video/mp4"
          />
        </video>
        <ul role="list" className="divide-y divide-gray-200 my-4">
          {videos.map((video) => (
            <li key={video.name} className="py-4 flex">
              <div className="ml-3 flex flex-row justify-start items-center space-x-3">
                <PlayIcon className="w-6 h-6 text-gray-600" />
                <p className="text-sm font-medium text-gray-900">
                  {video.name}
                </p>
              </div>
            </li>
          ))}
        </ul>
      </section>
    </DashboardLayout>
  );
}

export default withProtected(Video);

To create a dynamic reference based on the route, I utilize the following code:

// Reference
const reference = ref(storage, `training/${id}`);

This reference is then listed using the listAll method mentioned earlier:

useEffect(() => {
    function exec() {
      listAll(reference).then((snapshot) => {
        const videos = [];
        snapshot.items.forEach((video) => {
          videos.push(video);
        });

        setVideos(videos);
      });
    }

exec();
}, [reference]);

After pushing the elements to a state as an array, the state is iterated by a component. Everything seems to be functioning properly, but I encounter an infinite loop:

https://i.stack.imgur.com/tApLj.png

If anyone has insights into why this issue is occurring, please share your thoughts!

Answer №1

It's unclear what the problem is, but perhaps it would be more optimal to include only the id parameter in the useEffects array dependency list.

This approach may be more efficient since the videos are dependent on the route, so the useEffect will only need to re-run when the route changes.

Answer №2

It seems like the issue might be originating from this section of your code

useEffect(() => {
    function execute() {
      listAll(items).then((snapshot) => {
        const videos = [];
        snapshot.items.forEach((video) => {
          videos.push(video);
        });

        setVideos(videos); //updating `videos` triggers another call to `useEffect` due to its dependency
      });
    }

    execute();
  }, [items, videos]); //dependency on `videos` 

To resolve this, consider removing videos from the dependencies list in your useEffect

useEffect(() => {
    function execute() {
      listAll(items).then((snapshot) => {
        const videos = [];
        snapshot.items.forEach((video) => {
          videos.push(video);
        });

        setVideos(videos);
      });
    }

    execute();
  }, [items]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for obtaining the Tag from a React Component?

Not the HTML DOM element tag, the JSX tag, the react class name. As I work on creating an editor, adding items to the canvas array requires me to check and call the appropriate method based on what is being added. A simplified version of my idea: changeS ...

Leverage the power of Node.js by utilizing http.get along with

I have been working on integrating a library (available here) into my project, which is capable of generating QR codes and various other types of codes. My current issue revolves around making a request where I can access both the req and res objects in o ...

Would you be able to clarify why the run() function is giving me an error when I try to return {1,3}, but it works fine when I return {a,b} in

I'm really confused as to why the return {1,3} in the run() function is throwing an error when it works just fine for return {a,b} in the fun() function function fun(){ let a = 10; let b = 20; return {a, b}; } ...

No error reported upon trying to render json output

I'm having an issue where the following code is not displaying any output. Can someone help me identify what mistake I might be making? This is the HTML file: <head> <script type = "text/javascript"> function ajax_get_json() { var h ...

Each page in NextJS has a nearly identical JavaScript bundle size

After using NextJS for a considerable amount of time, I finally decided to take a closer look at the build folder and the console output when the build process is successful. To my surprise, I noticed something peculiar during one of these inspections. In ...

Encountering a 503 Error in Loading .js Files from Index.html in a .NET 7.0 Angular Application

I recently came into possession of an Angular project that I am trying to set up in IIS, but I am encountering some unusual behavior. Since I am relatively new to Angular, I ask for your patience as I navigate through this issue. Upon loading the website, ...

Tips on handling jsonp responses in CakePHP without using the .json extension

When working with CakePHP, the framework determines the data type to return by either checking for the presence of the .json extension in the URL or examining the Accepts HTTP header. It becomes a bit trickier when dealing with JSONP, as it doesn't a ...

Please refresh the page after acknowledging the error

I am facing an issue with my PHP page that triggers a javascript alert upon encountering an error. if (strpos($this->color,':') !== false) { echo '<script type="text/javascript">alert("Please use the RBG format of 255:2 ...

Mock needed assistance

In my testing scenario, I am attempting to simulate a service that is utilized by my function using sinon. However, I am encountering difficulties in inserting the mock into my function. The service is obtained through the use of require The structure of ...

What is the method for rotating a map using JavaScript?

My map built with Leaflet displays a route and a moving car marker. Now, I am looking to implement a feature where the map rotates based on the direction of the car. I have access to both the current coordinates of the car and the target coordinates. ...

Issue encountered when importing a font in TypeScript due to an error in the link tag's crossorigin

How do I troubleshoot a TypeScript error when importing a custom font, such as a Google font? <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> Below is the specific error message: Type 'boolean' is ...

Is it possible for PHP to dynamically load a file based on a condition set in JavaScript?

I am attempting to dynamically insert a PHP include onto the page once the user scrolls to a specific part of the page. Is this feasible? For example: var hasReachedPoint = false; $(window).scroll(function() { var $this = $(this); if ($this.scrollTo ...

Using a timer to make Ajax calls twice on a single webpage

Can multiple ajax calls be made simultaneously on the same page to different receiving div tags? I am struggling to find a solution to this issue. I have a total of 3 pages: a home page, and two PHP pages named status and alert which echo the results. Wi ...

Issues with the inheritance functionality in styled components are causing errors

The issue arises when I try to customize the styling of my PrimaryButton component, separate from the DefaultButton. Despite writing style properties for it, the changes do not take effect. Here is the folder structure: https://i.stack.imgur.com/0KjyH.pn ...

The hook from Supabase is facing issues with proper importing

This project is a Spotify clone. The issue I'm facing is related to importing the hook. The error message reads: React Hook "useSupabaseClient" is called in function "useloadArtistImage" that is neither a React function component nor a custom React H ...

Is it possible to create a central hub for all routes in a large AngularJS application?

Developing a large angularjs application with the intention of utilizing require.js for lazy-loading additional modules. The main question at hand is whether to create a comprehensive route.js file containing all the routes to other modules, or if each mod ...

What is the best way to keep the heights of two divs in sync?

Is there a way to make two divs have the same height, even though their content determines their individual heights? I am looking for a solution that doesn't involve using a table or a parent div. I'm new to JavaScript, so I'm hoping there i ...

JavaScript tip: Improve the way you highlight the current navigation page while scrolling by finding alternative methods to using "scrollY > x"

Currently, my webpage layout is divided into 4 sections - HOME, ABOUT, SKILLS, and CONTACT. Below is the JavaScript code I am using to highlight a specific section on the navigation bar based on the scroll position: let home = document.querySelector(" ...

Tips for removing a row from a table

I've been working on a responsive data table where each time I click an add button at the end of a row, a new row is added with the add button turning into a delete button. Below is the code I've implemented: The Table: <table id="invoice_ta ...

Error when using jQuery AJAX to parse JSONP callback

Take a look at this code snippet: $(function () { $.ajax({ type: "GET", url: "http://mosaicco.force.com/siteforce/activeretailaccounts", dataType: "jsonp", crossDomain: true, jsonp: "callback", error: f ...