Created
August 22, 2021 12:13
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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