In my application I have one main model, let's call them users
. I have a module users
and a submodule within it called list
.
On consumption of an api endpoint I get 10 users back as an array of users. For each user, I dynamically register a user
module for each one within the list
module within users
using the id
as the key.
this.registerModule(['users', 'list', user.id], UserModule);
Then I dispatch some action to hydrate the data in my store. This all works fine.
I have a getter that parses the list
module(an object that contains id
's as keys that point to a user
) into an array of users. It looks something like this:
users: (state) => {
const users = Object.keys(state.list).map(key => state.list[key]);
return users;
}
The problem
When vuex
dynamically registers the individual UserModule
's it orders them within the list
module alphabetically, not the order in which the modules get registered. This is a problem because I want the array of users to be in the same order as they come in from the api.
Example
If the endpoint returns 2 users like this:
[
{ id: '3', name: 'Bob'},
{ id: '1', name: 'Tom'}
]
Then the list module will look like this:
state: {
list: {
1: { id: '1', name: 'Tom'},
3: { id: '3', name: 'Bob'}
}
}
And the users
getter would then return:
[
{ id: '1', name: 'Tom'},
{ id: '3', name: 'Bob'},
]
My tentative solution is to inject an order property into each module as it gets consumed then in the getter sort by that order property. It doesn't feel great because I feel like I'm adding a loop to sort for no reason.
The questions
- Is there any way to order dynamically register modules as they come in rather than alphabetically by key?
- Can anyone think of a better solve for this problem beyond injecting an "order" property?