Soullivaneuh
Soullivaneuh

Reputation: 3863

Svelte derived stores and array sort

I set up a store containing a list of rides loaded from my API:

const loadRides = () => client.service('rides').find({
  query: {
    $sort: {
      date: -1,
    }
  }
});

const createRides = () => {
  const { subscribe, update } = writable([], async (set) => {
    try {
      const rides = await loadRides().then((result) => result.data);
      set(rides);
    } catch (e) {
      console.error(e);
    }
    // Socket update binding?
  });

  subscribe((rides) => console.debug('rides', rides));

  return {
    subscribe,
    refresh: () => loadRides().then((result) => update(() => result.data)),
  };
};
export const rides = createRides();

Then I set a two derived stores for past and future rides:

export const pastRides = derived(
  rides,
  ($rides) => $rides
    .filter((ride) => ride.steps.every((step) => step.doneAt))
  ,
);
export const comingRides = derived(
  rides,
  ($rides) => $rides
    .filter((ride) => ride.steps.some((step) => !step.doneAt))
    .sort((rideA, rideB) => {
      const compare = new Date(rideA.date) - new Date(rideB.date);
      console.log(rideA.date, rideB.date, compare);
      return compare;
    })
  ,
);

The sort method on the second one does not have any effect.

So I tried to put this method before the filter one. It works, but it also sort $pastRides. In fact, it is sorting the full $rides array and it make sens.

But I does not understand why the sort after filter does not work.

What did I miss?

Upvotes: 1

Views: 1726

Answers (1)

Tan Li Hau
Tan Li Hau

Reputation: 2334

Array.sort is mutable. Meaning, when you call rides.sort, it will sort and modify rides and return the sorted rides.

When you use derived(rides, ($rides) => ... ), the $rides you received is the original rides array that you call set(rides). So you can imagine that both the pastRides and comingRides received the same $rides array.

you can observe this behavior in this repl

To not having both derived interfere with each other, you can create a new array and sort the new array:

const sorted_1 = derived(array, $a => [...$a].sort());

you can try this out in this repl.

Upvotes: 1

Related Questions