F
F
feliciya2021-03-10 23:22:42
React Native
feliciya, 2021-03-10 23:22:42

How to change the state in the reducer?

Hey! This is my reducer
const initialState = {
items: {
First: 0,
Second: 0,
Third: 0
},
sum: 0
}

export default function fwReducer(state = initialState, action) {
switch (action.type) {
case ('INC '): {
const name = action.payload;
let newState = { ...state };
newState.items[name] += 1;
return { items: {...newState.items }, sum: state.total+1};
}
default: return state
}
}

I understand that now I am changing the state incorrectly, + in fact I am changing the array in the original store, mutating it, which is impossible. How should it be? Help me please)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2021-03-11
@Casufi

You started to rebuild the state

let newState = { 
  ...state,
   items: {
     ...state.items,
     [name]: state.items[name] + 1,
     sum: state.sum+1
   }
};

Didn't have enough patience?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question