eGlu
eGlu

Reputation: 807

Meteor collection reorders on component rerender

To get straight to the point, I want to ensure that regardless if the component re-renders the order of the collection is maintained.

I have a meteor createContainer element where I subscribe to a collection and then assign a variable to it.

export default PipelineTableContainer = createContainer(() => {
  const clientsSub = Meteor.subscribe('client.findByOrganisation');
  const clients = Clients.find({}, { sort: { createdAt: -1 } ).fetch();

  return {
    clients,
  };
}, ClientsView);

ClientsView is a line-graph which displays when the clients joined. Date matters here. For some reason when the ClientsView component re-renders based on a state change the order of the clients collection is then changed so it is no longer ordered by createdAt desc. This then causes an error with the charting library as the dates need to be in order.

To restate: I want to ensure that regardless if the component re-renders the order of the collection is maintained.

Any advice would be much appreciated thank you and regards.

Upvotes: 0

Views: 37

Answers (3)

eGlu
eGlu

Reputation: 807

Disclaimer: This does not solve the issue of the collection reordering but it does allow the app to function as wanted:

this.state.clients.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());

This ES6 function allows me sort the collection in ascending/descending order prior to it being used so regardless if the collection is reordered on a re-render this will always fire off and ensure the order is correct.

If someone knows why the collection is re-ordering that would still be appreciated.

Upvotes: 0

kcuhcx2
kcuhcx2

Reputation: 353

I also agree with TAnas's answer. I reckon all the sorting should be on the server side and not in the client side, you could also create an index on the server side to try speed things up E.g.

    collection.rawCollection().createIndex({ createdAt: -1 });

If you wanted to.

Upvotes: 1

Anas Tiour
Anas Tiour

Reputation: 1422

Just a quick guess, but if you order the results of the query in the publication itself this should fix your problem. If you are using that same publication for other components, you can create another one named client.findByOrganisationOrdered and call it in your component.

If you take this approach, you wouldn't need to sort on your client's collection since you guarantee that the results of the publication are already ordered.

Hope this helps. If it doesn't I'd like to take a look at the publication.

Upvotes: 0

Related Questions