Reputation: 317
When I am trying to update a property of an Object through dispatch, I can't see the update directly...
state.disable = action.payload;
return state;
the above code made me use a trick to update the state but that one has performance issue.
let tempState = Object.assign({},state);
tempState.disable = action.payload;
return tempState;
this one works fine and DOM direclty update after that. BTW app became so slow specially when I use it a lot and the state is a big object.
How can I solve this issue and force react update the dom even with a change in a property of an object?
Upvotes: 1
Views: 292
Reputation: 486
You can use Immer
With Immer, you can write something like
import produce from 'immer';
const initialState = {
text: ''
}
const textReducer = (state = initialState, action) => {
switch(action.type) {
case UPDATE_TEXT: {
return produce(state, draft => {
draft.text = action.payload;
});
}
}
}
By the way, you should NEVER do something like
state.something = somethingelse
That breaks immutable pattern, you can read more here
Upvotes: 1
Reputation: 1984
While effective, using Object.assign() can quickly make simple reducers difficult to read given its rather verbose syntax.
An alternative approach is to use the object spread syntax recently added to the JavaScript specification. It lets you use the spread (...) operator to copy enumerable properties from one object to another in a more succinct way. The object spread operator is conceptually similar to the ES6 array spread operator.
So this could work out.
return {
...state,
disable: action.payload
}
Upvotes: 1