jamiebuilds / unstated-next

200 bytes to never think about React state management libraries ever again
MIT License
4.18k stars 145 forks source link

Interdependent containers and asynchronous operations #80

Open djMax opened 4 years ago

djMax commented 4 years ago

I'm trying to implement unstated-next in a React Native app and having some conceptual struggles. I have three containers - LocationContainer (stores the current location, as available), IdentityContainer (holds some GUIDs that are generated asynchronously) and SessionContainer (stores the result of a network call that is based on location and the GUIDs).

The first two are fairly easy, I just have useEffect functions with no dependencies to kick off the requests to generate guids or ask for location. In the SessionContainer I have a "status" value which says whether I've kicked off the request, received an answer, etc. The problem is I can't start the request in SessionContainer until the other two containers have particular state values. How do I "await" a state value in another container? Is there something inherently wrong with this container interdependence?

olavoparno commented 4 years ago

Can you share a bit of your code or even better reproduce it in a codesandbox of some sort? Would this perhaps help you out?

https://github.com/jamiebuilds/unstated-next#tip-1-composing-containers

djMax commented 4 years ago

Ok, I think I've got a reasonably similar example here:

https://codesandbox.io/s/upbeat-fast-3ounh?file=/src/App.tsx

In addition to the question of whether this is the "right way" - I'm struggling to isolate some helper function to avoid the large amount of repeated code - useRef for the async promise, the "am I still mounted" stuff... In real life there is one additional complication which is that the LAST promise - the session one - generates multiple events from that original async operation which in turn feed other containers. So I have to find a way to essentially handle multiple responses (events) from that original promise with a potentially changing function due to other state changes...

djMax commented 4 years ago

I made a repo for this, hopefully I can improve it and some others might make MST/React Context/Redux (not it) examples.

https://github.com/djMax/react-state-tests