RoyalIcing / react-organism

Dead simple React state management to bring pure components alive
https://react-organism.now.sh/
MIT License
223 stars 3 forks source link

Asynchronous Actions #14

Closed busypeoples closed 7 years ago

busypeoples commented 7 years ago

Is it possible to declare or compose asynchronous actions with setState functions? For example something like run:

run(doAsyncFetch, (valueFromAsyncFetch) => ({ foo }) => { foo: foo + valueFromAsyncFetch})

I think this would be very beneficial. Also, what is load? Can't find any information on this. Seems it is able to take care of effects. Also what if one would like to use Tasks instead of Promises how can this be defined in user land. These are the last open questions. Great library!

RoyalIcing commented 7 years ago

Yes, a Promise may resolve to an updater function, like so:

doAsyncFetch()
  .then((valueFromAsyncFetch) => ({ foo }) => ({ foo: foo + valueFromAsyncFetch}))

What do you mean by Tasks instead of Promises? What do they do differently? Promise is great because it’s part of the ES spec. Thanks!

busypeoples commented 7 years ago

Should definitely support Promises. Just meant what if somebody uses Tasks. The main difference is that Tasks are lazy and you fork, then they start to run. See also https://glebbahmutov.com/blog/difference-between-promise-and-task/

But looking at your doAsyncFetch example, it might even work out of the box.

Task(foo).fork(() => ({}), (valueFromAsyncFetch) => ({ foo }) => ({ foo: foo + valueFromAsyncFetch}))
RoyalIcing commented 7 years ago

OK, yeah so technically react-organism will accept any thenable (anything having a .then method) — possibly there are enhancers or options for Task that add this? As that would open up interoperability with a lot of libraries then. I will see what the further demand is for Tasks before adding in support.

RoyalIcing commented 7 years ago

It looks as though a running Task supports converting into a Promise using the .promise() method.