Nicolas Pretot
Nicolas Pretot

Reputation: 192

Redux + modify state outsite reducer + angular

There is something I can't get with redux. I'm using ngRedux in an angular project.

Let say I have a store like :

export interface IState {
    myVar: any
}

export const INITIAL_STATE: IState {
    myVar: {
        value1: 0,
        value2: true
    }
}

If I get this chunk of the store using the @select decorator and subscribe to the observable :

@select('myVar') myVar$;

ngOnInit() {
    myVar$.subscribe((myvar) => {
        console.log("myVar changed")
    })
}

What is stopping me to do that :

@select('myVar') myVar$;

ngOnInit() {
    myVar$.subscribe((myvar) => {
        myvar.value2 = false; // <= This Modify the state
    })
}

I agree I should never do that, and this is just for example purpose, but is there a way to prevent this from being done? Maybe telling ngRedux to return readonly myVar or something else, because in a more complex example it's easy to mess up with the store like that.

My actual problem :

public class AnotherClass {

    protected value1: number;
    protected value2: boolean;

    constructor(obj: any) {
        this.value1 = obj.value1;
        this.value2 = obj.value2;
    }
}

public class MyVarWrapper: extends AnotherClass {

    constructor(myvar: any) {
        super(myvar);

        this.value2 = false; // <= [1] Modifying value2
    }
}

@select('myVar') myVar$;

ngOnInit() {
    myVar$.subscribe((myvar) => {
        let wrapper = new MyVarWrapper(myvar); // <= [2] Because of [1] modify the state
    });
}

Because all of that is reference, the store is modified and I would like the compiler of the IDE telling me that I messed up here. Or even better, that redux return me a copy of this var, that I can use and modify without risking to modify my state.

Upvotes: 0

Views: 56

Answers (1)

Zacol
Zacol

Reputation: 93

Maybe this library will be helpful: https://github.com/buunguyen/redux-freeze

It’s Redux middleware that prevents state from being mutated anywhere in the app.

There is also alternative library: https://github.com/brandonroberts/ngrx-store-freeze

Upvotes: 2

Related Questions