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

can't retrieve setter from useStore without retrieving state #1

Open
mazengh opened this issue Oct 21, 2022 · 2 comments
Open

can't retrieve setter from useStore without retrieving state #1

mazengh opened this issue Oct 21, 2022 · 2 comments

Comments

@mazengh
Copy link

mazengh commented Oct 21, 2022

The below code expects a selector... if no selector is used, an error is thrown.

const state = useSyncExternalStore(store.subscribe, () => selector(store.get()));

This can be fixed be just returning setting the getter to store.get when no selector is passed. Some like below.

const getter = selector ? () => selector(store.get()) : store.get;
const state = useSyncExternalStore(store.subscribe, getter);

@nicosh
Copy link

nicosh commented Nov 9, 2022

I prefer to keep the get and set methods separate, something like this :

  function useStore() {
    const store = useContext(StoreContext);
    if (!store) {
      throw new Error('Store not found');
    }
    function query<SelectorOutput>(selector: (store: Store) => SelectorOutput) {
      return useSyncExternalStore(
        store.subscribe,
        () => selector(store.get()),
        () => selector(initialState)
      );
    }
    const dispatch = store.set;
    return { query, dispatch };
  }

So in my other components i can just use get or set

  const { query, dispatch } = useStore();
  const fieldValue = query((store) => store['value']); // retrieve value 
  dispatch({ value :  'Jon'}); // set value

@Alim-El
Copy link

Alim-El commented May 9, 2023

@mazengh maybe it can help you: const useStoreSetter = () => useStore(() => null).at(1);

jherr pushed a commit that referenced this issue May 3, 2024
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

No branches or pull requests

3 participants