'NgRx sort and update Array inside object in state

Cant assign sorted array back to state.

The interface type IDataSet assigned to the subComponentData looks like this. arrOut is sorted but if I try to assign it back to gridDataArray it does not work. I get a type mismatch {}[] is not [{}].

export interface IDataSet {
gridDataArray: [
    {
        column1: string;
        column2: string;
        column3: string;
        column4: string;
        column5: string;
        name: string;
    }
];
urls: string[];
}

State object looks like this.

export interface IFeatureState {
  subComponentData: IDataSet;
  isSpinnerActivated: boolean;
}

Assigning the little test data I have below does work. But if I try and assign "arrOut" or "arr" back it does not compile and I get this error.

The types of 'subComponentData.gridDataArray' are incompatible between these types. Type '{ column1: string; column2: string; column3: string; column4: string; column5: string; name: string; }[]' is not assignable to type '[{ column1: string; column2: string; column3: string; column4: string; column5: string; name: string; }]'

on(sortGridData, (state: IFeatureState, { payload } ) => {
    const sortByKey = key => (a, b) => a[key] > b[key] ? 1 : -1;
    const arr = state.subComponentData.gridDataArray.slice();
    const arrOut = arr.sort(sortByKey(payload));
   return {
        ...state,
        subComponentData: {
            ...state.subComponentData,
            gridDataArray: arrOut

            //TEST DATA THAT WORKS
            // [{ column1:'Test', column2: 'Test', column3: 'Test',
            //     column4: 'Test', column5: 'Test', name: 'Test' }]
        }
    };
}),


Solution 1:[1]

RESOLVED

export interface IDataSet {
   gridDataArray: IDataElement[];
   urls: string[];
}

export interface IDataElement

{
    column1: string;
    column2: string;
    column3: string;
    column4: string;
    column5: string;
    name: string;
}

Then in the reducer just changed to this:

  on(sortGridData, (state: IFeatureState, { payload } ) => {
  const sortByKey = key => (a, b) => a[key] > b[key] ? 1 : -1;
  const arr = state.subComponentData.gridDataArray.slice();
  const arrOut = arr.sort(sortByKey(payload));
 return {
    ...state,
    subComponentData: {
        ...state.subComponentData,
        gridDataArray: [...arrOut]
    }
};

}),

I was very close but owe the answer to this. Now my sort only goes in one direction so I will be working on that next.

https://bobbyhadz.com/blog/typescript-source-has-elements-but-target-allows

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1