fluxxor
fluxxor copied to clipboard
Best practices for nested models
Hello, me again. I'm wondering which are the best practices when there are nested models, for example.
I've an action like this
load: function() {
this.dispatch(Constants.LOAD_PRODUCT)
request
.get(BASE_URL + '/product')
.send((err, response) => {
this.dispatch(Constants.LOAD_PRODUCT_SUCCESS, {products: response.body});
})
}
the dispatched products is a list of product
Product:
id: 1
name: "foo"
comments: ["comment/1", "comment/2"]
Now, I've to fetch for each product the comments. How? I think that this is really atrocious:
function retrieveComments(product) {
let comments = []
_.each(product.comments, (url) => {
request
.get(BASE_URL + '/' + url)
.send((err, response) => {
comments.push(response.body)
})
}
product.comments = comments
}
load: function() {
this.dispatch(Constants.LOAD_PRODUCT)
request
.get(BASE_URL + '/product')
.send((err, response) => {
_.each(response.body, retrieveComments)
this.dispatch(Constants.LOAD_PRODUCT_SUCCESS, {products: response.body});
})
}
So how can I handle nested models with flux ?
I need to define a CommentStore ? Than I trigger the loadComment event fomr the ProductStore and waitFor it before dispatch the LOAD_PRODUCT_SUCCESS
?
Hi again. :) This is going to be another opinionated answer, as flux really only talks about data flow, and not really the shape or access of that data.
If there's no way in your API to grab the full contents of all the comments for a product, then at some point you'll end up needing to load each one individually. When you choose to perform that operation depends a lot on how you want your app to behave. I'd say in that case it likely makes sense to do it when the comment is actually shown, though I prefer this pattern for loading data than having actions that "load" things.
My general recommendation, though, is to find a way to fetch the comments in aggregate (or even embed them in the product JSON response), and use a separate comment store to manage the global app state associated with them. If the comments don't do very much/you can't interact with them, you can probably get away with just keeping them as nested data in the product store, but if you want to e.g. edit, delete, and add comments, you'll probably want a comment store.