Add thunk support
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!');
},
});
@developit I saw you thumbs upped this, would it be able to get merged in?
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)