Skip to content

Commit

Permalink
refactor in more idiomatic way without relying on undocumented behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi committed Mar 27, 2021
1 parent 45e355f commit 130e2e1
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 13 deletions.
12 changes: 6 additions & 6 deletions .size-snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@
}
},
"utils.module.js": {
"bundled": 8383,
"minified": 3692,
"gzipped": 1489,
"bundled": 8382,
"minified": 3699,
"gzipped": 1481,
"treeshaked": {
"rollup": {
"code": 28,
Expand Down Expand Up @@ -103,9 +103,9 @@
"gzipped": 3467
},
"utils.js": {
"bundled": 11566,
"minified": 5645,
"gzipped": 2105
"bundled": 11579,
"minified": 5650,
"gzipped": 2098
},
"devtools.js": {
"bundled": 2394,
Expand Down
14 changes: 7 additions & 7 deletions src/utils/atomWithDefault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,23 @@ import type { Read } from '../core/types'
export function atomWithDefault<Value>(
getDefault: Read<Value>
): PrimitiveAtom<Value> {
const overwrittenAtom = atom(false)
const EMPTY = Symbol()
const overwrittenAtom = atom<Value | typeof EMPTY>(EMPTY)
const anAtom: PrimitiveAtom<Value> = atom(
(get) => {
if (get(overwrittenAtom)) {
return get(anAtom)
const overwritten = get(overwrittenAtom)
if (overwritten !== EMPTY) {
return overwritten
}
return getDefault(get)
},
(get, set, update) => {
set(overwrittenAtom, true)
(get, set, update) =>
set(
anAtom,
overwrittenAtom,
typeof update === 'function'
? (update as (prev: Value) => Value)(get(anAtom))
: update
)
}
)
return anAtom
}

0 comments on commit 130e2e1

Please sign in to comment.