4

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

  1. Is there any way to order dynamically register modules as they come in rather than alphabetically by key?
  2. Can anyone think of a better solve for this problem beyond injecting an "order" property?
Andrew Kim
  • 2,479
  • 3
  • 15
  • 36
  • `No, properties order in objects is not guaranteed in JavaScript; you need to use an Array.` https://stackoverflow.com/a/5525820/5599288 – Jacob Goh May 23 '18 at 13:41
  • right i know they're not guaranteed, but they've been pretty consistent, it's really just the way they get injected to the list module that is the problem – Andrew Kim May 23 '18 at 13:45
  • 1
    [Looks like it's about Javascript Object and not Vue](https://jsfiddle.net/jacobgoh101/horhggh1/). Numeric property always reordered, alphabet property won't reorder. – Jacob Goh May 23 '18 at 14:13
  • that's really helpful. thank you, actually did a better workaround just storing the ordered array of ids in state, then just mapping those to the dynamically registered module – Andrew Kim May 23 '18 at 16:13

0 Answers0