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

Missing subscribeKeys(store, keys, cb) method ? #262

Open
Jeremboo opened this issue Dec 20, 2023 · 3 comments · Fixed by #275
Open

Missing subscribeKeys(store, keys, cb) method ? #262

Jeremboo opened this issue Dec 20, 2023 · 3 comments · Fixed by #275

Comments

@Jeremboo
Copy link

We have both store.subscribe(cb) and store.listen(cb) to decide if we want to call the listeners immediately on subscribe or not.

So why not having the same with subscribeKeys(store, keys, cb) along listenKeys(store, keys, cb) ?

import { listenKeys, type StoreValue } from 'nanostores';

export function subscribeKeys<
  SomeStore extends { get: () => StoreValue<SomeStore>; setKey: (key: any, value: any) => void }
>(
  $store: SomeStore,
  propsToListen: SomeStore extends { setKey: (key: infer Key, value: never) => unknown } ? readonly Key[] : never,
  callback: (_props: StoreValue<SomeStore>) => void
) {
  listenKeys($store, propsToListen, callback);
  callback($store.get());
}

I'm using it in prod and it's working pretty good !

@ai
Copy link
Member

ai commented Dec 21, 2023

Do you have a real use case for that? If yes, we can add.

@Jeremboo
Copy link
Author

The use case is similar to using the already implemented store.subscribe(cb) method.
It's to trigger the callback immediately on subscribe.

I'm using it in vanillaJS. For instance to init my JS classes with values from the store.

Exemple :

export default class MyExample {
  valueA = 0;

  constructor() {
    subscribeKeys(webgl, ['valueA'], this.handlePropsChanged);
  }

  handlePropsChanged = ({ valueA }) => {
    if (valueA != this.valueA) {
      // Animate with the new values directly instantiation and all the other times
      gsap.to(this, { valueA, valueB, duration: 1 });
    }
  }
}

If it's a use case you don't want to support, maybe for consistency store.subscribe(cb) should be removed ?

@ai
Copy link
Member

ai commented Dec 22, 2023

Send PR with a function to next branch

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 a pull request may close this issue.

2 participants