React.useEffect not triggering when dependency has changed

Viewed 390

Edit: I found the solution to this! See my answer below.

So essentially, I have a slice of state that is updating but not triggering the useEffect that has it as a dependency:

const [editableParticipants, setEditableParticipants] = useState(*initial value*);
const [joinLeftTimeState, setJoinLeftTimeState] = useState(*initial value*);

function addParticipant(newParticipant) {
  setEditableParticipants([
    ...editableParticipants,
    newParticipant
  ])
}

useEffect(() => {
  setJoinLeftTimeState(
    editableParticipants.map(*mapping stuff*)
  );
}, [editableParticipants]);

When addParticipant is triggered, editableParticipants is successfully updating but the effect isn't running, leaving joinLeftTimeState without an entry for the new participant. I put a console log in the effect itself, it's not triggering at all after addParticipant runs. What the heck?

2 Answers

So the problem here was a little complicated, but I'll try my best to sum it up.

Essentially, the render was trying to do a .find on joinLeftTimeState for a participant that had been added before the effect fired off (editableParticipants is updated but joinLeftTimeState isn't yet), causing everything to crash. Adding default values if the .find turned up empty allowed the code to progress and now the effect is firing properly.

function Table() {
  const [editableParticipants, setEditableParticipants] = useState(*initial 
  value*);
  const [joinLeftTimeState, setJoinLeftTimeState] = useState(*initial value*);

  function addParticipant(newParticipant) {
    setEditableParticipants([
      ...editableParticipants,
      newParticipant
    ])
  }

  useEffect(() => {
    setJoinLeftTimeState(
      editableParticipants.map(*mapping stuff*)
    );
  }, [editableParticipants]);

  return editableParticipants.map(
    ptcpnt => <Row joinLeftTimeState={joinLeftTimeState} participant={ptcpnt} />
  )
}

function Row({ joinLeftTimeState, participant }) {
  const defaultTimes = { a: '', b: '' };
  const userTimes = joinLeftTimeState.find(
    ptcpnt => ptcpnt.id === participant.id
  )
  const { a, b } = userTimes || defaultTimes;

  return (*stuff*)
}

The joys of asynchronous state updates, right? Thanks for all the ideas!

useEffect(() => {
 // do something
}, [dependency])

I'm guessing your dependency isn't changing cause map function doesn't change the current array, you need to assign the result to a new var.

consider this snippet:

var arr = [1,2,3];
arr.map(x=>x*2)
(3) [2, 4, 6]

while arr is still:

(3) [1, 2, 3]
Related