Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating state in reducer using variables

I'm build a simple app that expands and collapses sections of content based on their state. Basically, if collapse = false, add a class and if it's true, add a different class.

I'm using Next.js with Redux and running into an issue. I'd like to update the state based on an argument the action is passed. It's not updating the state and I'm not sure why or what the better alternative would be. Any clarification would be great!

// DEFAULT STATE    
const defaultState = {
  membership: 'none',
  sectionMembership: {
    id: 1,
    currentName: 'Membership',
    nextName: 'General',
    collapse: false
  },
  sectionGeneral: {
    id: 2,
    prevName: 'Membership',
    currentName: 'General',
    nextName: 'Royalties',
    collapse: true
  }
}

// ACTION TYPES
export const actionTypes = {
  SET_MEMBERSHIP: 'SET_MEMBERSHIP',
  MOVE_FORWARDS: 'MOVE_FORWARDS',
  MOVE_BACKWARDS: 'MOVE_BACKWARDS'
}

// ACTION
export const moveForwards = (currentSection) => dispatch => {
  return dispatch({ type: actionTypes.MOVE_FORWARDS, currentSection })
}

// REDUCERS
export const reducer = (state = defaultState, action) => {
  switch (action.type) {
      case actionTypes.SET_MEMBERSHIP:
        return Object.assign({}, state, {
          membership: action.membershipType
        })
      case actionTypes.MOVE_FORWARDS:
        const currentId = action.currentSection.id
        const currentName = "section" + action.currentSection.currentName    
        return Object.assign({}, state, {
          currentName: {
            id: currentId,
            collapse: true
          }
        })
    default: return state
  }
}

The currentName variable is causing an issue for the state to not update. I want to be able to dynamically change each sections state, which is why I thought I'd be able have a variable and update state like this.

It seems you can't use a variable for the key in the key/value pair. Why is this? What's an alternative to dynamically updating state?

like image 661
onehunnid Avatar asked Sep 16 '25 07:09

onehunnid


1 Answers

That is because JavaScript understands that you want to create a key named currentName not a key with the value of the variable currentName. In order to do what you want, you have to wrap currentName in brackets:

return Object.assign({}, state, {
          [currentName]: {
            id: currentId,
            collapse: true
          }
        })

So it will understand that the key will be whatever currentName is.

like image 101
Tiago Alves Avatar answered Sep 19 '25 15:09

Tiago Alves