Skip to content

Commit

Permalink
types: fix types in useAtom hook
Browse files Browse the repository at this point in the history
  • Loading branch information
StyleShit committed Aug 22, 2024
1 parent 4c12148 commit 876fa5e
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/perfect-ducks-poke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'atomsphere': patch
---

Fix types in `useAtom` hook
21 changes: 20 additions & 1 deletion src/__tests__/use-atom.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, expectTypeOf, it } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { atom } from '../atom';
import { useAtom } from '../use-atom';
Expand Down Expand Up @@ -75,4 +75,23 @@ describe('useAtom', () => {
expect(result.current).toBe(2);
});
});

it('should have proper types', () => {
// Arrange.
const countAtom = atom(0);
const stringCountAtom = atom((get) => String(get(countAtom)));

const { result: countResult } = renderHook(() => useAtom(countAtom));

const { result: doubleCountResult } = renderHook(() =>
useAtom(stringCountAtom),
);

// Assert.
expectTypeOf(countResult.current).toEqualTypeOf<
[number, (value: number | ((prev: number) => number)) => void]
>();

expectTypeOf(doubleCountResult.current).toEqualTypeOf<string>();
});
});
12 changes: 6 additions & 6 deletions src/use-atom.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { useSyncExternalStore } from 'react';
import type { WritableAtom, ReadableAtom } from './atom';

export function useAtom<T>(
atom: WritableAtom<T>,
): [WritableAtom<T>['get'], WritableAtom<T>['set']];

export function useAtom<T>(atom: ReadableAtom<T>): ReadableAtom<T>['get'];
type Setter<T> = WritableAtom<T>['set'];

export function useAtom<T>(atom: WritableAtom<T> | ReadableAtom<T>) {
export function useAtom<T>(atom: WritableAtom<T>): [T, Setter<T>];
export function useAtom<T>(atom: ReadableAtom<T>): T;
export function useAtom<T>(
atom: WritableAtom<T> | ReadableAtom<T>,
): [T, Setter<T>] | T {
const isWriteableAtom = 'set' in atom;
const value = useSyncExternalStore(atom.subscribe, atom.get);

Expand Down

0 comments on commit 876fa5e

Please sign in to comment.