Feature request - destroy/reinitialize atom.
See original GitHub issueHello, thanks for recoil, simple & powerful!
I have a use case where I open a document, split it into atom tree, then I can modify the nodes of the document. If I decide that the changes are bad, I can discard the changes & start again by reading the document into recoil.
The trouble is that when I reopen the document, the app displays the cached state from previous steps, because recoil has the old values under the atom keys. So to get ‘fresh atoms’ I can choose new keys, which is bad since the previous will still consume memory.
Other thing I do now, is that I pass the opened document through selector, where I have access to the reset
api, which I apply to my document tree after I turn it into atoms, thus I set the atom values to the default
(initial) value.
Also not sure how to handle this case properly, because now I’m getting lot’s of warnings:
Duplicate atom key "node-c272f880-9518-4658-a33c-459a008889c9". This is a FATAL ERROR in
production. But it is safe to ignore this warning if it occurred because of
hot module replacement.
So maybe my approach is incorrect.
The error flow is:
// 1. initialize document into atoms
const textAtom = atom({key: '1', default: {type: "TEXT", id: '1', value: "Hello world"});
// 2. update the node
const setText = useSetRecoilValue(textAtom);
setText("Bad text");
// 3. Reopen the document
// 4. Initialize the atoms (as step 1)
const textAtom = atom({key: '1', default: {type: "TEXT", id: '1', value: "Hello world"});
// 5. render app
const text = useRecoilValue(textAtom);
console.log(text) // "Bad text".
The workaround flow is:
// 5. reset atom in selector
export const persistedTextSelector = selector<Node>({
key: "persistedTextSelector",
get: ({get}) => get(persistedTextAtom),
set: ({set, get, reset}, node) => {
const textAtom = atom({key: node.id, default: node);
set(persistedTextAtom, textAtom);
reset(textAtom)
}
})
// 6. render app
const text = useRecoilValue(persistedTextAtom);
console.log(text) // "Hello world".
What I would like to have is some flag on atom: atom({key: ‘1’, default: {type: “TEXT”, id: ‘1’, value: “Hello world”},reinitialize: true})
But that still won’t save me from getting the duplicate error warning. So I guess some
Recoil.removeKeys([...ids]);
api could work?
Thanks
Issue Analytics
- State:
- Created 3 years ago
- Reactions:12
- Comments:15 (5 by maintainers)
Top GitHub Comments
Symbols won’t work for keys as they would not persist across multiple executions and
WeakMap
isn’t sufficient for this use case. Something likeFinalizationRegistry
would be really convenient. Unfortunately, it doesn’t have enough browser support yet to use. In the meantime we’ve added garbage collection functionality for this. It’s currently behind a feature flag, but should be exposed in an upcoming release.need this feature