Skip to content

Support reducers for primitive atoms #38

Closed
@dwelle

Description

Allow primitive atoms to define reducers (setters), which will allow to transform the update. I don't think you should need to create a pair of a primitive and a derived atoms (where you don't export the primitive atom at all) just to accomplish this.

It seems it's somewhat supported even now, but it's undocumented and not typed correctly:

type List = { id: string; value: number }[];
const sortedListAtom = atom<List, List>([], (get, set, update) => {
  return set(
    sortedListAtom,
    update.sort((a, b) => a.value - b.value)
  );
});

Sandbox

Use case: transform updates so that callers don't have to do it themselves in each call site. In the above example, we want to update the list and ensure it's sorted. The updater may be much more complex and you don't want to force (and ensure) consumers do that themselves.

Metadata

Assignees

No one assigned

    Labels

    has snippetThis issue includes code snipppets as solutions or workarounds

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions