Skip to content

Add getter api to @xstate/store #5184

Closed
expelledboy wants to merge 1 commit intostatelyai:davidkpiano/store-v3from
expelledboy:davidkpiano/store-v3
Closed

Add getter api to @xstate/store #5184
expelledboy wants to merge 1 commit intostatelyai:davidkpiano/store-v3from
expelledboy:davidkpiano/store-v3

Conversation

@expelledboy
Copy link

@expelledboy expelledboy commented Feb 2, 2025

Merge getters implementation from #5183 onto #5175

@changeset-bot
Copy link

changeset-bot bot commented Feb 2, 2025

⚠️ No Changeset found

Latest commit: ac5993d

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

@expelledboy
Copy link
Author

Obv you get a circular reference between the getters type and the second arg of its definition.

Depending on how many second pass getters you have there are two approaches

Define the type of ctx for parents

const store = createStore({
  context: { price: 10, quantity: 2 },
  getters: {
    subtotal: (ctx: { price: number; quantity: number }) =>
      ctx.price * ctx.quantity,
    tax: (_, getters) => getters.subtotal * 0.1,
    total: (_, getters) => getters.subtotal + getters.tax
  },
  on: {
    updatePrice: (ctx, ev: { value: number }) => ({ price: ev.value })
  }
});

Or just define the type of getters

const store = createStore({
  context: { price: 10, quantity: 2 },
  getters: {
    subtotal: (ctx) => ctx.price * ctx.quantity,
    tax: (_, getters: { subtotal: number }): number =>
      getters.subtotal * 0.1,
    total: (_, getters: { subtotal: number; tax: number }): number =>
      getters.subtotal + getters.tax
  },
  on: {
    updatePrice: (ctx, ev: { value: number }) => ({ price: ev.value })
  }
});

Probably would want to include this in the docs.

Unless anyone has a better idea on the API here.

@expelledboy
Copy link
Author

@davidkpiano Please can you assist me merging this? I dont want there to be massive merge conflicts in 2-4 months with the v3 branch.

Mostly I need assistance getting the types working in the surrounding utils.

And / or if you agree to the API itself.

@davidkpiano davidkpiano deleted the branch statelyai:davidkpiano/store-v3 February 9, 2025 02:55
@davidkpiano davidkpiano closed this Feb 9, 2025
@expelledboy
Copy link
Author

Guessing this was closed because of the merge.

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