2

I have what seems to be a simple setup.

  • Some state the that holds the selected task.
  • A useEffect that opens the modal when the state is updated.

The modal opens, and inside the TaskScreen I'm able to console log selectedTask.

The problem is the onOpened prop never has the selectedTask. It always logs undefined.

How can TaskScreen have the correct value but not the onOpened prop? They're both rendered at the same time.

const taskModalRef = useRef(undefined);
const [selectedTask, setSelectedTask] = useState(undefined);

useEffect(() => {
  if (selectedTask) {
    taskModalRef.current.open();
  }
})

<Modalize
  ref={taskModalRef}
  onOpened={() => {
    console.log('selectedTask', selectedTask); //  always undefined.
  }}
>
  <TaskScreen task={selectedTask} /> //  always has the correct value.
</Modalize>

GollyJer
  • 23,857
  • 16
  • 106
  • 174
  • just try const [selectedTask, setSelectedTask] = useState(null) to see if it logs null – cuongtd Jul 02 '20 at 02:12
  • Hey. Thanks for the response but I'm not exactly sure what you're saying... of course it logs null in that case. It logs whatever I put as the default value. The problem is I want it to have the new value. I have a button that calls `setSelectedTask` which then triggers the useEffect and opens the modal passing in the selectedTask. I was thinking it was memoized but looking at the Modalize source it doesn't seem to be. – GollyJer Jul 02 '20 at 04:52
  • I guess onOpened run before selectedTask is set – cuongtd Jul 02 '20 at 04:54
  • But then it would be undefined in both cases. – GollyJer Jul 02 '20 at 04:54
  • Could it be that react memoize the value of `onOpened ` and re-run the same function everytime. While in `task={selectedTask}` the value is updated for every render. – Kevin Amiranoff Mar 03 '21 at 23:05
  • I guess you would need an additional `useEffect(() => {setSelectedTask(selectedTask)}, [selectedTask])` to update the internal state of your component to recreate the value of `onOpened` on state change. – Kevin Amiranoff Mar 03 '21 at 23:07
  • I bookmarked this question originally but I guess you only see the obvious 6 months later. – Kevin Amiranoff Mar 03 '21 at 23:09

0 Answers0