Skip to content

Commit

Permalink
feat(hooks): add useAssertSingleton
Browse files Browse the repository at this point in the history
This is copied from the main invokeai repo, with a small change - hook IDs may be symbols.
  • Loading branch information
psychedelicious committed Sep 10, 2024
1 parent 95b3cd6 commit beb7d62
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions lib/hooks/use-assert-singleton.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useEffect } from 'react';

const IDS = new Set<string | symbol>();

/**
* Asserts that there is only one instance of a singleton entity. It can be a hook or a component.
* @param id The unique ID of the singleton entity.
*/
export function useAssertSingleton(id: string | symbol) {
useEffect(() => {
if (IDS.has(id)) {
throw new Error(`There should be only one instance of ${String(id)}`);
}

IDS.add(id);

return () => {
IDS.delete(id);
};
}, [id]);
}

0 comments on commit beb7d62

Please sign in to comment.