Idan
Idan

Reputation: 5450

Listener does not trigger useEffect with dependency array

The goal here is to change table data when data is modified in Firebase

The issue is that for some reason, within the scope of firebase listener, setState(...) does not trigger the useEffect(()=> {}, [...]) with the appropriate dependencies.

Any idea why, and is there a way to force the change?

 const [actions, setActions] = useState([]);
 ....
 firebase.
    .firestore()
    .collection("collection_name")
    .onSnapshot(s => {
      if (!s.empty) {
        s.docChanges().forEach(change => {
          if (change.type === "modified") { 
            const newActions = [...actions, change.doc.data()]
            setActions(newActions) //The change 
            console.log("arrived here")
          }...

...

useEffect(() => {
  console.log("change in actions"); // Does not triggered on when modified
}, [actions]);

This does work without the dependency array:

useEffect(() => {
  console.log("This does work")
});

Upvotes: 1

Views: 554

Answers (1)

Palencar
Palencar

Reputation: 159

I think you should look other your references.

The thing with react hook is that if the reference of the object before and after the setter is the same, the useEffect listening to this object wont trigger.

Meaning that if in newActions = ... you use the reference leading to actions to update the value of action and then setActions() the reference of the object stay the same, instead you should try to make a copy of actions and then modify this independent copy. You can then setActions(modifiedCopy) and this will normally trigger the useEffect.

note: that's only a guess cause i can't know what you putted behind newActions = ...

Upvotes: 1

Related Questions