Skip to content

Instantly share code, notes, and snippets.

@ctemplin
Created August 22, 2021 12:13
Show Gist options
  • Save ctemplin/fcbede1044ab6c64721fd667f69fe240 to your computer and use it in GitHub Desktop.
Save ctemplin/fcbede1044ab6c64721fd667f69fe240 to your computer and use it in GitHub Desktop.
Recoil selector to capture the default values of atoms and merge them with arbitrary props.
import { atom, selector, selectorFamily, snapshot_UNSTABLE } from 'recoil'
const atomDefaults = {}
export const resetThenSetValue = selector ({
key: 'resetThenSetValue',
set: ({set}, {atom, ...rest}) => {
set(atom,
(prevValue) => {
// Defaults not already stored
if (!atomDefaults[atom.key]) {
const isDefault = snapshot_UNSTABLE().getInfo_UNSTABLE(atom).isSet
// Store incoming value as defaults.
atomDefaults[atom.key] = isDefault ? {...prevValue} :
// Backup in case atom was ininitally set by another method.
Object.fromEntries(Object.entries(prevValue).map(
_ => [_[0], _[1] instanceof Array ? [] : null]
))
Object.freeze(atomDefaults[atom.key])
}
return {...atomDefaults[atom.key], ...rest}
}
)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment