2

I have a state which contains an array of data. I need to remove all data from that array when certain action done. I use Angular 2.

const intialState: State = {   
    someData: new Array<someData>()
};

export function stateReducer(state = intialState, action: StateActionList.StateActionList) {
    switch (action.type) {
    case StateActionList.REMOVE_DATA:
            console.log(state.someData);
            return {
                ...state,
                someData: new Array<someData>()
            }
        }
}

In my component I have following code:

this.store.dispatch(new StateActions.RemoveData());

In State actions:

export const REMOVE_DATA="REMOVE_DATA";
export class RemoveData implements Action {
    readonly type=REMOVE_DATA;
}

That code doen't return for me cleaned array someData from the store. The array contains same data as it was before

rick1
  • 946
  • 3
  • 15
  • 31

2 Answers2

0

Try explicitly returning an empty array as the new state:

case StateActionList.REMOVE_DATA:: {
  return {
    someData: []
  };
}
guilhebl
  • 8,330
  • 10
  • 47
  • 66
-1

This looks a bit doubtful

someData: new Array<someData>()

someData is a variable name and a type?

See Declare an array in TypeScript

let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();

let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();

let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];

let arr10 = <boolean[]> [];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();

const state = {   
  someData: new Array()
};

console.log('empty', state.someData)
state.someData.push('a')
console.log('contains "a"', state.someData) 

const remove = () =>  {
  console.log('constians "a"', state.someData);
  return {
    ...state,
    someData: new Array()
  }
}

const newState = remove()
console.log('empty', newState.someData)
Richard Matsen
  • 20,671
  • 3
  • 43
  • 77