Search code examples
arraysangularsetstatengxs

ngxs setstate first element in array


In NGXS , I need to set the new element in "items: any[]" the first index of an array every time. something like (unshift)

Example:

items[] = [{'aa':val},{'bb':val}]

Now Am inserting {'cc':val} Then expected array should be like

items[] = [{'cc':val}, {'aa':val},{'bb':val}]

Declaration

export class BasketStateModel {

  public **items: any[]**;
  public basketSize: number;

}

BASKET ACTION

const state = getState();

 setState({ items: **[...state.items, payload]**, basketSize: state.items.length + 1 });

}

Solution

  • This is how you can insert element(s) at first place in array :

    Destructuring_assignment :

    let myArr = [{'a':'a'},{'b':'b'}]
    
    myArr = [{'c':'c'}, ...myArr]
    
    console.log(myArr)