flux icon indicating copy to clipboard operation
flux copied to clipboard

[Question] store.getItem() which may require an async server call

Open abergs opened this issue 12 years ago • 17 comments

Hi. I want to discuss the best practice for a situation where data will be lazily fetched and if the way I'm currently doing it is a good way to do it.

  1. view calls store.getItem(123)
  2. store realize it haven't loaded item 123
  3. store sets loading = true
  4. store calls API.LoadItem({id:123})
  5. store emits that it has changed (due to loading = true)
  6. store returns null
  7. view handles null result
  8. view receives change event and can show user that store is loading
  9. [Async at 4] API.LoadItem fires ajax request. When request is resolved, fires Actions.ItemLoaded({result: ...})
  10. store receives callback on ItemLoaded, stores the result, sets loading to false and emit that it has changed.
  11. view receives change event, and updates it state, effetively recalling store.getItem(123).

Is this the proper way to solve such problem? I can see one issue above, which is number 6 & 7, because if getItem returns null, the view don't know if the resource doesn't exist or if it's pending. Would it be wise to wrap all get-calls with a status wrapper that could tell if we know for sure that 123 doesn't exist (we already tried ajax request and it failed) or if we just have to fire an request before we have the result.

abergs avatar Sep 17 '14 11:09 abergs

Just a few thoughts on this ... the store could hold a record of any item ids waiting for a response and could expose this through a function to views. ie getItemsBeingFetched.

Then if this array has any items in it the view could show a loading state, or if it is only concerned with a particular id it would check for that?

davetayls avatar Sep 17 '14 12:09 davetayls

@davetayls yeah, we are having a discussion on #reactjs and the store would create an representation of item 123, such as: {id: 123, status: loading} and clients could then query the store for loading items and we could easily cancel repetitive loading calls for the same item if it's already loading.

abergs avatar Sep 17 '14 12:09 abergs

@abergs that sounds like a good idea, my only thought would be when another view requests allItems what would you return? I guess all currently known items to exist. Would also be good to think about how this would cater for delete or put changes?? :+1:

davetayls avatar Sep 17 '14 12:09 davetayls

@abergs Stores should not directly create actions. This will lead to a dispatch-within-a-dispatch problem and an unstable state. You can just make the async call to the web API directly from the store (or by directly calling a method in a Utils module), and then create an action within the error/success callback.

I like the idea of {id: 123, status: loading}, as it will allow the user to continue to work with the rest of the app.

fisherwebdev avatar Sep 17 '14 17:09 fisherwebdev

@fisherwebdev Any chance you could integrate this into one of the examples? You might recall I asked something very similar on StackOverflow regarding this type of flow.

Ideally it would cover the original points from @abergs, but also writing asychronous data using actions and why cascading events are a bad idea.

simenbrekken avatar Sep 26 '14 08:09 simenbrekken

The excellent interview of Ian Obermiller also has a lot of helpful tips on this subject.

simenbrekken avatar Sep 26 '14 08:09 simenbrekken

@abergs Also check out https://github.com/ianobermiller/nuclearmail

simenbrekken avatar Sep 27 '14 10:09 simenbrekken

^^^ nice! I hadn't seen that project of Ian's before. Thanks for that link.

fisherwebdev avatar Oct 25 '14 23:10 fisherwebdev

I've tried implementing the approach outlined in the interview with Ian and the Nuclearmail project. At first avoiding actions for reads make a lot of sense as it simplifies many aspects of an app.

However as soon as multiple components attempt to read the same data at the same time the approach becomes quite complex.

Consider two lists of todos where both show the exact same list of todos. List A would attempt to fetch todos from the store, the store calls an API function and stores the list of todos. List B however is attempting to do the exact same thing at the same time, this forces you to not only cache the underlying data but also currently active requests/promises so that you don't perform duplicate requests.

This becomes increasingly complex when something like pagination is added to the mix. Let's say you again have two paginated lists of todos, but this time list A shows todos 10-20 and B 1-20, obviously there's no point in fetching 10-20 as they will be included in the 1-20 request.

simenbrekken avatar Oct 27 '14 09:10 simenbrekken

@fisherwebdev by saying :

You can just make the async call to the web API directly from the store (or by directly calling a method in a Utils module)

do you imply that calling the webapi utils from a store dispatchToken is fine ? I just did it and it fixed my issue with Dispatch called during dispatch. However it feels kind of weird doing that in the perspective of that diagram : image

chollier avatar Nov 25 '14 21:11 chollier

The most important Flux data flow diagram is this:

Action -> Dispatcher -> Store -> View

The rest, while suggesting best practices, are really just implementation details. How data leaves the system and goes to the server does not matter very much. What matters more is how it enters the system and flows through it. Always start the flow with dispatched actions.

fisherwebdev avatar Dec 01 '14 03:12 fisherwebdev

I played around a bit with this approach today:

Edit: I realize this has some Reflux specific code but it should be quite similar in "pure" Flux

Store:

var ProductStore = Reflux.createStore({
  init() {
    this.products = {};
  },

  get(id) {
    // Attempt to fetch product from cache
    var product = this.products[id];

    // If no product was found, create a placeholder while we load it
    if (!product) {
      product = this.products[id] = {
        id: id,
        loading: true
      };

      // Fetch the product from our API
      API.get('/products/' + id)
        .then(res => {
          this.products[id] = res.data;
          this.trigger();
        });
    }

    // Return either the actual product or the placeholder
    return product;
  }
});

Component:

var ProductDetailPage = React.createClass({
  getInitialState() {
    return this.getStateFromStores();
  },

  getStateFromStores() {
    var productId = this.getQuery().productId;

    return {
      product: ProductStore.get(productId)
    };
  },

  onStoreChange() {
    this.setState(this.getStateFromStores());
  },

  componentDidMount() {
    this.listenTo(ProductStore, this.onStoreChange);
  },

  render() {
    var product = this.state.product;

    return product.loading ? <Loader /> : <ProductDetails product={product} />;
  }
});

I've yet to play around with list type responses yet, but I'm leaning towards wrapping list results in a type of "query"-object that includes the list of data along with hasMore, total etc. for the given query.

simenbrekken avatar Feb 05 '15 14:02 simenbrekken

This is really interesting. In my angular apps I tend to work heavily with promises. I essentially have stores that maintain a promise based cache of things, and each method makes the relevant API request if necessary to populate the cache. for example:

var itemCache = {}

function makeApiRequest(url){
    return new Promise(function(res, err){
        //fetch data from server..
        res(data);
    });
}

function copy(item){
    //deep copy item...
    return angular.copy( item );
}

function getItem(id){

    //promise for item in cache? return a copy of it
    if(itemCache[id]) {
        return itemCache[id].then(copy)
    }

    //else, immediately cache promise for item:
    var itemPromise = itemCache[id] = makeApiRequest("url/for/item/"+id);
    return itemPromise;
}

//common usage (we can act on "loading" state easily):

isLoadingData = true;
getItem(12).then(function(item){
     isLoadingData = false 
    /* do something with item */ 
})


The things I like about this approach are

  1. Something using this store doesnt care where the data is coming from. It might take a few seconds or it might be instant, but it's handled the same in either case. No need to keep track of loading state. An interested view can do that very easily if it cares, as above.
  2. It's really easy in most cases to ensure that a request for something never happens more than once. The moment there is a promise in the cache, every subsequent request will just be handed that same thing.

However, the downsides are that you end up working with promises throughout the system, which means everything becomes asyns. Also, I imagine storing promises is a less economical approach in terms of memory.

In practise I haven't found these to be a problem (yet), but I am intrigued to see whether a flux style architecture, which eliminates promises and async code from everything but the web API code, can do it better, so I'll be having a go at it for my next project.

@simenbrekken I like your approach. It makes total sense to me to make the XHR request from inside the store, as the store is the thing that knows what exactly it needs to get, and in my mind is responsible for, well, storing whatever data is asked for. Knowing exactly what data it is storing might allow it to be cleverer with regard to making XHR requests as well (eg batching multiple requests for different item details).

jsdw avatar Jun 22 '15 19:06 jsdw

Thank you for reporting this issue and appreciate your patience. We've notified the core team for an update on this issue. We're looking for a response within the next 30 days or the issue may be closed.

ghost avatar Aug 05 '15 18:08 ghost

Is there any update on this issue?

igo88 avatar Nov 12 '15 04:11 igo88

@igo88 This is one approach that we use quite heavily at Facebook: https://github.com/staltz/flux-challenge/tree/master/submissions/kyldvs

Relevant files are SithStore and SithDataManager.

kyldvs avatar Nov 12 '15 06:11 kyldvs

Going to close this out since I feel like the example above demonstrates solutions to most aspects of async data in flux. If you would still like to discuss this issue further please feel free to re-open!

kyldvs avatar Nov 18 '15 22:11 kyldvs