immerjs / immer

Create the next immutable state by mutating the current one

Home Page:https://immerjs.github.io/immer/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unexpeted result when updating object

Stophface opened this issue · comments

I am using Immer in redux-toolkit and I am trying to update the state with one action in two places.
This is how the state object I want to update looks like

const initialState: AddedActivitiesState = {
    animals: {
        dogs: {
            sheepDog: {
                items: AddedSheepDogs[],
                bulkActions: SheepDogBulkActions,
                allSelected: false,
            },
            retrievers: {
                items: AddedRetrieverDogs[],
                bulkActions: RetrieverBulkActions,
                allSelected: boolean,
            },
        },
    },
};

HOW_SORT {
    ASC = 'asc', DESC = 'desc'
}

interface SheepDogBulkActions {
      name: HOW_SORT |  null,
      age: HOW_SORT | null,
      height: HOW_SORT.DESC,
}

interface RetrieversBulkActions  {
    name: HOW_SORT | null,
    age: HOW_SORT | null,
    height: HOW_SORT | null,
    color: HOW_SORT | null,
    origin: HOW_SORT.DESC,
}

type BulkActionsType = keyof SheepDogBulkActions  | keyof RetrieversBulkActions  

This is the action I am dispatching


       ...
        sortAnimals: (state, action: PayloadAction<{
            animal: 'dog' | ...
            subAnimal: 'sheepDog' | 'retrievers' | ...
            whichAction: BulkActionsType,
            sortOrder: HOW_SORT
        }
        >) => {
            const {animal, subAnimal, whichAction, sortOrder} = action.payload
            state.animals[animal][subAnimal] = orderSubAnimals(animal, subAnimal, state.animals[animal][subAnimal], whichAction, sortOrder)
        },
    ....

And this is orderSubAnimals()

export const orderSubAnimals= (
    animal: 'dog' | ...,
    subAnimal:  'sheepDog' | 'retrievers' | ...,
    animals: ...,
    whichAction: BulkActionsType,
    sortOrder: HOW_SORT
) => {
    const activeSortOrders = ...
    animals.subAnimals= orderBy(animals.subAnimals, [...activeSortOrders...])
    animals.bulkAction[whichAction] = sortOrder
    return animals
}

What I do not understand is, that it only updates animals.bulkAction[whichAction] = sortOrder. This animals.subAnimals= orderBy(animals.subAnimals, [...activeSortOrders...]) has no effect. When I remove these lines animals.bulkAction[whichAction] = sortOrder, the order function has an effect and these lines animals.subAnimals= orderBy(animals.subAnimals, [...activeSortOrders...]) update the object.

Why is that?

Sorry for the late response. Looks more like a redux-toolkit question?