#Reset a store to its initial value

9 messages · Page 1 of 1 (latest)

young laurel
#

Hey all 👋
Just as the title suggests, I'm trying to find a way to set a store to its initial value. I have tried the following:

setState(initialValue)
setState(reconcile(initialValue))
setState(reconcile(initialValue, { merge: false }))
setState(() => initialValue)

I could technically go through each property and set it to its initial value but I was hoping I don't have to do that. Any help would be greatly appreciated!

austere reef
#

You can save the initial value as a variable and just set it to that

#

In the component

#

`
const InitialValue = {foo: "bar"}
const [r, w] = createStore(initialValue)

const reset = () => w(initialValue)
`

young laurel
lofty spindle
# young laurel This was the first thing I tried but the store didn't seem to change 😢

initial value should be cloned if you want to reuse it

const initialValue = {foo: "bar"}
const [r, w] = createStore(initialValue)
w("foo", "baz")
initialValue.foo // => "baz"

const initialValue = {foo: "bar"}
const [r, w] = createStore({ ...initialValue })
w("foo", "baz")
initialValue.foo // => "bar"

as for resetting, this might work

const initialValue = { foo: "bar" }
const [r, w] = createStore({ ...initialValue })
w("foo", "baz")
w(initialValue)
r.foo // => "bar"

but won't for nested objects

const initialValue = { foo: "bar", nested: { a: 123 } }
const [r, w] = createStore({ ...initialValue })
w("nested", "a", 321)
initialValue.nested.a // => 321
w(initialValue)
r.nested.a // => 321

const getInitialValue = () => { foo: "bar", nested: { a: 123 } }
const [r, w] = createStore(getInitialValue())
w("nested", "a", 321)
w(getInitialValue())
r.nested.a // => 123
young laurel
#

oh I see! so the issue is that I'm referring to the same object so the equality check is true, right?

#

thank you!

lofty spindle