unistore icon indicating copy to clipboard operation
unistore copied to clipboard

Add thunk support

Open eschaefer opened this issue 7 years ago • 2 comments

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!');
  },
});

eschaefer avatar Aug 17 '18 20:08 eschaefer

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

cj avatar Sep 30 '18 20:09 cj

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)

danielweck avatar Apr 29 '20 07:04 danielweck