Skip to content

Removing an onChange listener #450

@delucis

Description

@delucis

Do you want to request a feature or report a bug?

Bug/feature, depending on your perspective

What is the current behavior?

We can add a listener for the toast count via toast.onChange, but there doesn’t seem to be a way to remove/replace the listener. If I’ve understood the eventManager correctly, each time onChange is called, a new listener is pushed to the queue.

What is the expected behavior?

It should be possible for onChange to return a function that will remove the added listener. (Or some other mechanism to remove a listener should be provided.)

Use case

Using onChange inside useEffect:

function Notifications () {
  const [count, setCount] = useState(0)

  useEffect(() => {
    toast.onChange(c => {
      if (c !== count) setCount(c)
    })
  }, [count])

  return null
}

The useEffect hook will update the onChange each time count changes to make sure it is using up-to-date values. Best practice would be to return a function from useEffect that cleaned up onChange before adding the new listener.

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions