How do I sort a cached array in RTK Query?

832 Views Asked by At

I'm building an app with RTK Query where the user can drag and drop to reorder their 'shelves'. I want to optimistically update the shelf order but am confused about what I'm allowed to do to the proxy array Immer exposes.

I cloned it with .slice and was able to change the order values but sorting the cloned array by the new order values doesn't seem to work (the order of the items doesn't change).

async onQueryStarted(shelvesToReorder, {dispatch, queryFulfilled}) {
  const patchResult = dispatch(
    firestoreApi.util.updateQueryData('getShelves', undefined, draft => {
      const shelvesCopy: Array<ShelfSchema> = draft.slice();
      shelvesToReorder.forEach((shelf: {id: string, index: number}) => {
        const shelfToUpdate = shelvesCopy.find(item => item.id === shelf.id);
        if (shelfToUpdate) {
          shelfToUpdate.order = shelf.index;
        }
      })
      const sortedShelves = shelvesCopy.sort((a,b) => a.order - b.order);
      draft = sortedShelves;
    })
  )
  try {
    await queryFulfilled
  } catch {
    patchResult.undo()
  }
}

Besides solutions to this problem I'm also curious where I can learn more about how to interact with this proxy array since I'm very confused about why some of these methods work and others don't. For instance, I understand that I need to use methods like "current" from Immer to look at the state but is there any way to look at the current status of my clone? Console.log doesn't work.

Thanks for your help!

1

There are 1 best solutions below

0
On

UPDATE: The issue was my direct assignment of the draft variable, which isn't allowed: https://immerjs.github.io/immer/pitfalls/#dont-reassign-the-recipe-argument

An alternative would be to simply return the new state (sortedShelves). Immer offers the option to either return the new state or alter the draft variable, but you can't do both in the same function (so using a method like .slice on the draft variable to create a clone isn't allowed if you'll be returning a new state).