klmrmt
klmrmt

Reputation: 19

Infinite loop in useEffect fix?

I am currently pulling data from a firebase realtime database and the data will initial populate. When I refresh the page though, the contents disappear. I added an empty array at the end of the UseEffect() to stop the infinite loop issue that we were having, but it seems to stop updating our array when refreshed.

useEffect(() => {
    let jobs = [];
    firebase.database().ref("1h5GOL1WIfNEOtcxJVFQ0x_bgJxsPN5zJgVJOePmgJOY/Jobs").on("value", snapshot => {
      snapshot.forEach(snap => {
        jobs.push(snap.val());
      });
    })

    populateJobs(jobs);
  },[]);

Upvotes: 0

Views: 69

Answers (4)

Suraj.Shau
Suraj.Shau

Reputation: 1

The second argument of useEffect(()=>{},[]) which takes an array of argument tells react on what changes your callback passes there should run.

If passed an empty array it runs only once, behaving like componentdidmount method

When a variable is passed, it runs every time the value of the variable is changed.

Also if we pass an object as second parameter it will check for the reference change too.

Upvotes: 0

N G
N G

Reputation: 156

I assume populateJobs is function declared in your scope.

If so, you may want to wrap it in useCallback to ensure the function reference doesn't change.

const populateJobsFixed= useCallback(populateJobs, [])

useEffect(() => {
    ...
    populateJobsFixed(jobs);
  },[populateJobsFixed]);

Upvotes: 1

Daniel Duong
Daniel Duong

Reputation: 1104

populateJobs is a dependency of the useEffect

You need to have the dependency list be

},[populateJobs]);

Instead of an empty array

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 599956

As ray commented, it does matter how populateJobs is defined. But at a first guess, you'll need to call that from inside the callback:

  useEffect(() => {
    firebase.database().ref("1h5GOL1WIfNEOtcxJVFQ0x_bgJxsPN5zJgVJOePmgJOY/Jobs").on("value", snapshot => {
      let jobs = [];
      snapshot.forEach(snap => {
        jobs.push(snap.val());
      });
      populateJobs(jobs);
    })

  },[]);

Upvotes: 1

Related Questions