Handling one API call being dependant on data from another
- Dominant language
- JavaScript
- Stars
- 6.8k
- Forks
- 573
- PR merge metrics
- No merged PRs in 30d
Description
I trying to design an app where the user first need to login, when logged in a list of different **locations** are shown. When the user clicks on a location the "main page" is shown where I need to fetch all kinds of different resources from the API.
I've gotten the authentication/login part working OK and when the user is authenticated I emit 'user:authenticated' which I also listen for and emit 'locations:fetch'. This works great for showing the list of locations, now to the "hard" part.
One of the resources that I need to fetch in the main app is **devices**. I get which devices to fetch info for from the location resource so I need to have the locations available before I can make the API call for the devices. From what I've just said it seems as if they are always available but the user shall be able to go directly to a location (ignoring the list of locations page) using the path `/location/123`. Now the 'locations:fetch' call has NOT been emitted so I need to emit that first.
This is where I think it gets hard with the **'resource:fetch' --> 'resource:fetched'** pattern. I've tried things like
emitter.once('locations:fetched', function () { });
emitter.emit('locations:fetch')
but it feels very brittle. I'm also thinking of using callbacks and instead of emitting things like 'locations:fetch', 'devices:fetch', etc I emit 'init:location' and have something like:
emitter.on('init:location', function (locationId) {
getLocation(locationId, function (location) {
getDevices(location.devices, function (devices) {
state.devices.items = devices
emitter.emit('render')
...
}
}
}
but this goes against the fetch/fetched even pattern. It seems like a very simple problem to me so there's probably good solution to it that I just haven't thought about.
Contributor guide
Assessment
This issue has not been assessed yet.