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

Add thunk support #109

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

eschaefer
Copy link

@eschaefer eschaefer commented Aug 17, 2018

Maybe this opens a can of worms. I don't know. I found it useful. Real middleware would make it cooler.

let helpers = {
  setUser: (val) => ({ user: val }),
  setMessage: (val) => ({ message: val }),
};

let actions = store => ({
  simpleAction: (state, value) => ({ count: state.count + 1 }),
  thunkAction: (state, value) => async (action) => {
    let response = await fetch('/foo.json').then(res => res.json());

    action(helpers.setUser(response));
    action(helpers.setMessage('Thanks!');
  },
});

* master:
  Fix for jest tests failing.
@cj
Copy link
Contributor

cj commented Sep 30, 2018

@developit I saw you thumbs upped this, would it be able to get merged in?

@danielweck
Copy link

Can't this already be done with Unistore's existing async action functions?
Here's a rewrite of your example above (I've kept the function name thunkAction):

let helpers = {
  setUser: (val) => ({ user: val }),
  setMessage: (val) => ({ message: val }),
};

let actions = store => ({
  simpleAction: (state, value) => ({ count: state.count + 1 }),

  async thunkAction(state, value) {
    let response = await fetch('/foo.json').then(res => res.json());

    const updatedState = {
        ...helpers.setUser(response),
        ...helpers.setMessage('Thanks!'),
    };
    return updatedState; // or with store.setState(updatedState)
  },
});

Isn't the async flow equivalent to this PR's "thunk'ed" approach?

Also, in your example action is invoked twice (for setUser and setMessage), so I am wondering if this is to make a particular point, or just a random example? (as you can see in my modified code snippet above, I combined the state update into a single object)

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.

3 participants