Answer the question
In order to leave comments, you need to log in
How to change element in reducer?
My state is displayed in this form prntscr.com/cc1tmc . I can’t figure out how to change the data correctly, for example, here prntscr.com/cc1tx7 . Given that the first key (in this case 0) is in my $first variable, and the second key (in this case also 0) is in my $last variable. In the reducer itself, I get the desired element like this state[action.key1][action.key2] . but I don’t know how to change it correctly in state
Answer the question
In order to leave comments, you need to log in
DEMO .
const initalState = {
foo: 'bar',
baz: 'pew',
structure: [
['', ''],
['', ''],
],
};
const reducer = (state, action) => {
switch (action.type) {
case 'ADD_INPUT':
return {
...state,
structure: state.structure.map((v1, k1) => {
if (k1 === action.first) {
return v1.map((v2, k2) => {
if (k2 === action.second) {
return action.value;
} else {
return v2;
}
});
} else {
return v1;
}
}),
};
break;
default:
return state;
}
};
const newState = reducer(initalState, {
type: 'ADD_INPUT',
first: 0,
last: 0,
value: 'foo',
});
console.log(initalState);
console.log(newState);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question