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] Store select #5200

Merged
merged 8 commits into from
Feb 24, 2025
Merged

[@xstate/store] Store select #5200

merged 8 commits into from
Feb 24, 2025

Conversation

davidkpiano
Copy link
Member

@davidkpiano davidkpiano commented Feb 14, 2025

Added selectors to @xstate/store that enable efficient state selection and subscription:

  • store.select(selector) function to create a "selector" entity where you can:
    • Get current value with .get()
    • Subscribe to changes with .subscribe(callback)
    • Only notify subscribers when selected value actually changes
    • Support custom equality functions for fine-grained control over updates via store.select(selector, equalityFn)
const store = createStore({
  context: {
    position: { x: 0, y: 0 },
    user: { name: 'John', age: 30 }
  },
  on: {
    positionUpdated: (
      context,
      event: { position: { x: number; y: number } }
    ) => ({
      ...context,
      position: event.position
    })
  }
});

const position = store.select((state) => state.context.position);

position.get(); // { x: 0, y: 0 }

position.subscribe((position) => {
  console.log(position);
});

store.trigger.positionUpdated({ x: 100, y: 200 });
// Logs: { x: 100, y: 200 }

Copy link

changeset-bot bot commented Feb 14, 2025

🦋 Changeset detected

Latest commit: 0979f8d

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 marked this pull request as ready for review February 16, 2025 15:16
@davidkpiano
Copy link
Member Author

@Andarist Final review? 🥺

@davidkpiano davidkpiano merged commit 0332a16 into main Feb 24, 2025
1 check passed
@davidkpiano davidkpiano deleted the davidkpiano/store-select branch February 24, 2025 05:35
@github-actions github-actions bot mentioned this pull request Feb 24, 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.

2 participants