Skip to content

Commit

Permalink
fix: prevent DefaultValue from being set when the localStorage state …
Browse files Browse the repository at this point in the history
…does not contain the key. Fixes polemius#26
  • Loading branch information
bartvanremortele committed Apr 16, 2021
1 parent 500c146 commit 17198f5
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AtomEffect } from 'recoil'
import { AtomEffect, DefaultValue } from 'recoil'

export interface PersistStorage {
setItem(key: string, value: string): void | Promise<void>
Expand Down Expand Up @@ -33,7 +33,7 @@ export const recoilPersist = (
if (trigger === 'get') {
const state = getState()
if (typeof state.then === 'function') {
state.then((s) => {
state.then((s: any) => {
if (s.hasOwnProperty(node.key)) {
setSelf(s[node.key])
}
Expand All @@ -44,15 +44,18 @@ export const recoilPersist = (
}
}

onSet((newValue) => {
const state = getState()

if (newValue instanceof DefaultValue) {
if(state.hasOwnProperty(node.key)) delete state[node.key];
onSet(async (newValue) => {
const state = await getState()
if (
newValue !== null &&
newValue !== undefined &&
newValue instanceof DefaultValue
) {
if (state.hasOwnProperty(node.key)) delete state[node.key]
} else {
state[node.key] = newValue
}

setState(state)
})
}
Expand All @@ -73,6 +76,9 @@ export const recoilPersist = (
}

const parseState = (state: string) => {
if (state === undefined) {
return {}
}
try {
return JSON.parse(state)
} catch (e) {
Expand Down

0 comments on commit 17198f5

Please sign in to comment.