Reputation: 711
When updating my state inside a slice's reducer with the redux's toolkit, I ran into the problem of the circular reference, for example:
const aSlice = createSlice({
...
extraReducers: builder => {
...,
builder.addCase(addToState.fulfilled, (state, action) => {
state.data = {
...state.data,
...action.payload.data
};
});
...,
}
});
Thus resulting in ...state.data
returning a proxy reference instead of the value which is one of the pitfalls mention, Redux Toolkit doc as well as in Immer.js pitfalls section.
I can think of some ways to hack this into working but, I was wondering if they were any best practice for this matter or any elegant way of making this work?
Upvotes: 2
Views: 925
Reputation: 67469
When using Immer and proxies, a useful pattern for "assign all" is to actually use Object.assign()
.
Typically, use of Object.assign()
with Redux involves passing an empty object as the first parameter to make it an immutable update, like Object.assign({}, oldItem, newItem)
.
However, with Immer, you can do a truly mutating update to assign all incoming properties to the existing object. In this case, Object.assign(state.data, action.payload.data)
.
Upvotes: 6