Skip to content

Commit

Permalink
Ensure effects are always cleaned up
Browse files Browse the repository at this point in the history
  • Loading branch information
clauderic committed Sep 12, 2024
1 parent e70b29a commit 4d1a030
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/fix-unregister-bug.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@dnd-kit/abstract': patch
---

Make sure the cleanup function of effects is invoked when registering a new instance with the same `id` before the old instance has been unregistered.
9 changes: 8 additions & 1 deletion packages/abstract/src/core/entities/entity/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,18 @@ export class EntityRegistry<T extends Entity> {
*/
public register = (key: UniqueIdentifier, value: T) => {
const current = this.map.peek();
const currentValue = current.get(key);

if (current.get(key) === value) {
if (currentValue === value) {
return;
}

if (currentValue) {
const cleanup = this.cleanupFunctions.get(currentValue);
cleanup?.();
this.cleanupFunctions.delete(currentValue);
}

const updatedMap = new Map(current);
updatedMap.set(key, value);

Expand Down
5 changes: 2 additions & 3 deletions packages/react/src/core/hooks/useInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,8 @@ export function useInstance<T extends Instance>(

useEffect(() => {
instance.manager = manager;

// Register returns an unregister callback
return instance.register();
const unregister = instance.register();
return unregister;
}, [instance, manager]);

return instance;
Expand Down

0 comments on commit 4d1a030

Please sign in to comment.