'Weird behavior with redux not updating store state
I just ran into an issue, with my redux store not updating after a matched action is dispatched.
I managed to get my reducer to work, here it is:
// working approach
import { AnyAction } from 'redux';
export interface IReducerState {
config: (Record<string, any> & {
name: string;
age: string;
}) | null
}
const initialState = {
config: null,
};
const reducer = (state: IReducerState = initialState, action: AnyAction): IReducerState => {
const { type, payload } = action;
switch (type) {
case 'MATCHED_ACTION':
return {
...state,
config: {
...state.config,
name: payload.clear ? '' : state.config.name,
age: payload.clear ? '' : state.config.age,
[payload.field]: payload.value,
},
};
default:
return { ...state };
}
};
export default reducer;
But before, however, I was doing the following:
// alternative approach
case 'MATCHED_ACTION':
const result = { ...state.config };
if (payload.clear) {
result.name = '';
result.age = '';
}
if (payload.field && payload.value) {
result[payload.field] = payload.value;
}
return {
...state,
config: result
};
What am I doing wrong? Why is the alternative approach incorrect?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
