Skip to content

Commit

Permalink
fix(useSet): "has" method in useSet updated to reference latest set o…
Browse files Browse the repository at this point in the history
…bject
  • Loading branch information
Stefan Loeschcke committed Dec 10, 2019
1 parent 8c35bc9 commit 4f1d8c2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
17 changes: 12 additions & 5 deletions src/useSet.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,32 @@
import { useState, useMemo } from 'react';
import { useState, useMemo, useCallback } from 'react';

export interface Actions<K> {
has: (key: K) => boolean;
export interface StableActions<K> {
add: (key: K) => void;
remove: (key: K) => void;
reset: () => void;
}

export interface Actions<K> extends StableActions<K> {
has: (key: K) => boolean;
}

const useSet = <K>(initialSet = new Set<K>()): [Set<K>, Actions<K>] => {
const [set, setSet] = useState(initialSet);

const utils = useMemo<Actions<K>>(
const stableActions = useMemo<StableActions<K>>(
() => ({
has: item => set.has(item),
add: item => setSet(prevSet => new Set([...Array.from(prevSet), item])),
remove: item => setSet(prevSet => new Set(Array.from(prevSet).filter(i => i !== item))),
reset: () => setSet(initialSet),
}),
[setSet]
);

const utils = {
has: useCallback(item => set.has(item), [set]),
...stableActions,
} as Actions<K>;

return [set, utils];
};

Expand Down
20 changes: 18 additions & 2 deletions tests/useSet.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,21 @@ it('should have an initially provided key', () => {
expect(value).toBe(true);
});

it('should have an added key', () => {
const { result } = setUp(new Set());

act(() => {
result.current[1].add('newKey');
});

let value;
act(() => {
value = result.current[1].has('newKey');
});

expect(value).toBe(true);
});

it('should get false for non-existing key', () => {
const { result } = setUp(new Set(['a']));
const [, utils] = result.current;
Expand Down Expand Up @@ -110,12 +125,13 @@ it('should reset to initial set provided', () => {
it('should memoized its utils methods', () => {
const { result } = setUp(new Set(['a', 'b']));
const [, utils] = result.current;
const { add } = utils;
const { add, remove, reset } = utils;

act(() => {
add('foo');
});

expect(result.current[1]).toBe(utils);
expect(result.current[1].add).toBe(add);
expect(result.current[1].remove).toBe(remove);
expect(result.current[1].reset).toBe(reset);
});

0 comments on commit 4f1d8c2

Please sign in to comment.