S
SolidJS•8mo ago
jon vuri

How to set a store back to a default state at the top level (or clear it)?

Hi, I'm trying to use a store to represent the state of a dynamic number of inputs, where the inputs all map to a column in a db. A store seems like a good fit for this at first glance - I can store the input values keyed by the column id, and quickly get a set of signals for a dynamic number of inputs (then use those to determine form validity). My problem is when I submit - at that point I want to reset the entire store, thus also resetting all the controlled inputs to be blank as well, in preparation for the next input. How do I do this? For example:
const [inputs, setInputs] = createStore<Record<string, string>>({})

const updateInput = (column_id: string, value: string) => {
setInputs({ [column_id]: value })
}

const resetInputs = () => {
// ..?
}
const [inputs, setInputs] = createStore<Record<string, string>>({})

const updateInput = (column_id: string, value: string) => {
setInputs({ [column_id]: value })
}

const resetInputs = () => {
// ..?
}
5 Replies
jon vuri
jon vuri•8mo ago
Because updates are shallowly merged, even from the function version of setInputs, I'm not sure how to destructively set the entire store to a value (in this case, an empty object), like the original input to createStore. But that's the rough effect I'm seeking
apollo79
apollo79•8mo ago
I think there is no straightforward way, but you could do setInputs(Object.keys(inputs), undefined) That should do it Since setting a key to undefined deletes it and you can use an array of keys as path, which is what Object.keys(inputs) gives you
jon vuri
jon vuri•8mo ago
I see. that's definitely a bit obscure (as in, not obvious what it's doing, and would need a comment), but at least it's just one line. Thank you!
apollo79
apollo79•8mo ago
No problem 🙂
aryzing
aryzing•7mo ago
For the TS curious,
setState(Object.keys(state) as Array<keyof typeof state>, undefined);
setState(Object.keys(state) as Array<keyof typeof state>, undefined);