Redux Style-Guide states:
Avoid putting non-serializable values such as Promises, Symbols, Maps/Sets, functions, or class instances into the Redux store state or dispatched actions. This ensures that capabilities such as debugging via the Redux DevTools will work as expected. It also ensures that the UI will update as expected.
Every other object must use the immerable symbol to mark itself as compatible with Immer. When one of these objects is mutated within a producer, its prototype is preserved between copies.
class Foo {
[immerable] = true // Option 1
constructor() {
this[immerable] = true // Option 2
}
}
Foo[immerable] = true // Option 3
I know I can have a class instance reducer...but should I?
I'm assuming the dangers of this is that time-traveling & Redux DevTools may be broken - but immer will protect against any mutations outside the reducer.
import { immerable } from "immer";
class MyClass {
constructor() {
this[immerable] = true;
this.data = [];
}
addData(row = "") {
this.data.push(row);
}
prettyPrint() {
this.data.map((txt, index) => console.log(`Row ${index}: ${txt}`));
}
}
const example = createSlice({
name: "example",
initialState: new MyClass(),
reducers: {
addItem: (state, action) => {
state.addData(action.payload);
}
}
});
let state = example.reducer(undefined, example.actions.addItem("Test"));
console.log(state.prettyPrint());
state = example.reducer(state, example.actions.addItem("Test Me too"));
console.log(state.prettyPrint());
console.log(state);
//Will error
// state.addData('Will Error');
The reason for doing this? We have complex business logic inside large classes. Like in the example, prettyPrint, we have some complex functionality that is encapsulated in the class instance that we use across the react apps.
My other idea for the approach is to instantiate and serialize inside the reducer so that the json representation of our class instances are only ever stored inside the reducers. If I can avoid having to perform instantiate -> serialize every action though, and have access to utility functions on the state tree, this would be preferred.