N
N
n1ksON2020-12-24 17:24:41
React
n1ksON, 2020-12-24 17:24:41

How to return value of dynamic reducer?

There is a reducer (this version of the code is not working):

const initialState = {
  param1: '1',
  param2: '2',
  param3: {
    paramParam1: '4',
    paramParam2: '5' // в param3 всегда изменяется только paramParam2
  }
}
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'EXAMPLE':
      if (action.name === 'param1' || 'param2') {
        state[action.name] = action.value
      } else {
        state[action.name].paramParam2 = action.value
      }
      return state
  }
  default:
    return state
}
export const actionCreator = (value, name) => ({ type: 'EXAMPLE', value: value, name: name })
// в name приходит свойство, в value - значение


How to change the state in this case?

Tried with Object.keys().length but it doesn't work the way I want.
I want to reduce the case to the form:
return {
  ...state,
  action.name: action.value
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Lewandowski, 2020-12-24
@n1ksON

return {
  ...state,
  [action.name]: action.value,
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question