Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 redux and immutable.js state

I use ng2-redux and I'm trying to make redux state immutable. I can't do it because I don't know which interface is implemented by immutable state.

For example, I have a redux state:

let IState = {
    a: {
        b: string
    };
    d: string;
};

let state: IState  = {
  a: {
    b: 'c'
  },
  d: 'e'
}

Then immutable state is:

let immutableState = Immutable.fromJS(state);

Or maybe:

let immutableState = Immutable.Map(state);

I should know immutable state interface to work with redux:

constructor(ngRedux: NgRedux<IState>) {
like image 312
Ildar Avatar asked Apr 29 '26 04:04

Ildar


1 Answers

If you don't want to use generic Immutable.Map, You could use Immutable.js Record to create a class.

e.g.

// define an interface
interface IState = {
    a: {
        b: string
    };
    d: string;
};

// next, use the Record constructor passing in the defaults for the class
const stateRecord = Record({
  a: null,
  d: ''
});

// construct a class that extends the return from the Record call
export class MyState extends stateRecord implementsIState {
  a: Map<string, string>;
  d: string;
  constructor(config: IState) {
    super(config);
  }
}

Then in your NgRedux use the class you made.

constructor(ngRedux: NgRedux<MyState>) { ...

Since you are extending the stateRecord, the class is immutable. More information on how Records work in the ImmutableJs docs at https://immutable-js.github.io/immutable-js/docs/#/Record

like image 154
joshvito Avatar answered May 01 '26 05:05

joshvito