Skip to content

Commit

Permalink
fix: add undefined initial value to primitive Atom definition
Browse files Browse the repository at this point in the history
  • Loading branch information
rtritto committed Jul 20, 2024
1 parent 628aa3e commit 2e71e7c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/vanilla/atom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,19 +81,23 @@ export function atom<Value, Args extends unknown[], Result>(
write: Write<Args, Result>,
): WritableAtom<Value, Args, Result> & WithInitialValue<Value>

// primitive atom without default value
export function atom<Value>(): PrimitiveAtom<Value | undefined> &
WithInitialValue<Value | undefined>

// primitive atom
export function atom<Value>(
initialValue: Value,
): PrimitiveAtom<Value> & WithInitialValue<Value>

export function atom<Value, Args extends unknown[], Result>(
read: Value | Read<Value, SetAtom<Args, Result>>,
read?: Value | Read<Value, SetAtom<Args, Result>>,
write?: Write<Args, Result>,
) {
const key = `atom${++keyCount}`
const config = {
toString: () => key,
} as WritableAtom<Value, Args, Result> & { init?: Value }
} as WritableAtom<Value, Args, Result> & { init?: Value | undefined }
if (typeof read === 'function') {
config.read = read as Read<Value, SetAtom<Args, Result>>
} else {
Expand Down
9 changes: 9 additions & 0 deletions tests/vanilla/basic.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { expect, it } from 'vitest'
import { atom } from 'jotai/vanilla'

it('creates atoms', () => {
// primitive atom without default value
const undefinedAtom = atom()
// primitive atom
const countAtom = atom(0)
const anotherCountAtom = atom(1)
Expand All @@ -20,12 +22,19 @@ it('creates atoms', () => {
set(countAtom, get(countAtom) - 1)
})
expect({
undefinedAtom,
countAtom,
doubledCountAtom,
sumCountAtom,
decrementCountAtom,
}).toMatchInlineSnapshot(`
{
"undefinedAtom": {
"init": undefined,
"read": [Function],
"toString": [Function],
"write": [Function],
},
"countAtom": {
"init": 0,
"read": [Function],
Expand Down

0 comments on commit 2e71e7c

Please sign in to comment.