Skip to content
This repository has been archived by the owner on Sep 17, 2022. It is now read-only.

Usage with async actions #3

Closed
dkourilov opened this issue Nov 14, 2019 · 2 comments
Closed

Usage with async actions #3

dkourilov opened this issue Nov 14, 2019 · 2 comments

Comments

@dkourilov
Copy link

dkourilov commented Nov 14, 2019

Hey Rahim,

To continue developit/unistore#136 (comment), here is the problem I'm currently facing with async functions and useAction.

I'm trying to realize what useAction should look like for async actions. Say for some reasons I don't want to use await statement for any Promises inside useAction to finally return the state, and instead is looking to somehow update the state asynchronously.

The pattern I have in mind is to return the state from useAction as usual for any state updates before the Promises, and use state = store.getState(); /* update state */; store.setState(state) in Promise then/finally. To some extent, this looks ugly to me, and in case you were thinking on any clear pattern to minimize the code boilerplate and improve readability for async functions, I'll greatly appreciate your feedback.

Let me know if you need a pseudocode or even more concrete TS example.

@mihar-22
Copy link
Owner

Hey @dkourilov,

If I understand correctly you're trying to understand how Promises work with useAction? useAction supports promises directly.

const performAsyncOperation = async ({ count }) => {
  // perform some stuff ...
  return { count: count + 1 } // here we update the state.
}

const asyncAction = useAction(performAsyncOperation)

asyncAction() // call it or do whatever.

// Promise works the same as async just resolve the new state.
const somePromise = ({ count }) => new Promise((resolve, reject) => {
  resolve({ count : count + 1 })
})

const action = useAction(somePromise)

action() // call it.

Hope that helps. useAction just returns a Unistore action. You can read here https://github.com/developit/unistore/#usage.

@dkourilov
Copy link
Author

Awesome, this is exactly an example I was looking for. Everything is clear now, thanks for your help!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants