Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[xstate/store] Atoms #5221

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open

[xstate/store] Atoms #5221

wants to merge 9 commits into from

Conversation

davidkpiano
Copy link
Member

Added createAtom() for creating reactive atoms that can be combined with other atoms and stores:

  • Create simple atoms with initial values:

    import { createAtom } from '@xstate/store';
    
    const countAtom = createAtom(0);
    countAtom.get(); // 0
    countAtom.set(1); // or use setter function: (prev) => prev + 1
  • Subscribe to atom changes:

    countAtom.subscribe((value) => console.log(value));
  • Combine multiple atoms:

    const nameAtom = createAtom('hello');
    const countAtom = createAtom(3);
    const combinedAtom = createAtom((read) =>
      read(nameAtom).repeat(read(countAtom))
    );
    combinedAtom.get(); // "hellohellohello"
  • Seamlessly combine atoms with stores:

    const countAtom = createAtom(0);
    const nameStore = createStore({
      context: { name: 'David' }
      // ... store config
    });
    
    const combinedAtom = createAtom(
      (read) => read(nameStore).context.name + ` ${read(countAtom)}`
    );
    combinedAtom.get(); // "David 0"

Atoms automatically update when their dependencies change, making it easy to create derived state from both atoms and stores.

Copy link

changeset-bot bot commented Mar 8, 2025

🦋 Changeset detected

Latest commit: 4c518d3

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@xstate/store Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@davidkpiano davidkpiano requested a review from Andarist March 8, 2025 12:49
@davidkpiano davidkpiano self-assigned this Mar 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant