Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update nested object in Redux reducer

I have the following reducer:

import {
  // QuestionForm
  UPDATE_QUESTION_FORM,
  // FoodPreferenceList
  UPDATE_FOOD_PREFERENCE,
  UPDATE_NUMBER_OF_MEALS
} from '../actions/types';

const INITIAL_STATE = {
  setupComplete: false,
  error: '',
  loading: false,
  // QuestionForm
  questionForm: {
    gender: 'Female',
    age: '35',
    weight: '75',
    height: '175',
    activityLevel: '1.2',
    goal: '100',
    maintenanceCalories: '',
    goalCalories: '',
  },
  // FoodPreferenceList
  selectedFoodsArrays: [],
  numberOfMeals: '1'
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    // QuestionForm
    case UPDATE_QUESTION_FORM:
      return { ...state, questionForm.[action.payload.prop]: action.payload.value };
    // FoodPreferenceList
    case UPDATE_FOOD_PREFERENCE:
      return { ...state, selectedFoodsArrays: action.payload };
    case UPDATE_NUMBER_OF_MEALS:
      return { ...state, numberOfMeals: action.payload };
    // DEFAULT
    default:
      return state;
  }
};

I am having a bit of trouble referencing one of the objects stored in my state. The problem is with the line:

case UPDATE_QUESTION_FORM:
  return { ...state, questionForm.[action.payload.prop]: action.payload.value };

I get the following ESLint Error. I am trying to update an element of the questionForm entry with a value. The element updated in questionForm is decided by an argument. The format seems to be incorrect and Google Search has not helped out.

Example

questionForm.[gender]: 'Male'
  • This will update the gender key of questionForm with the value 'Male'.
like image 669
oisin097 Avatar asked Jan 04 '23 01:01

oisin097


1 Answers

What you would do is add another level of nesting:

case UPDATE_QUESTION_FORM:
  return { 
    ...state, 
    questionForm: {
      ...state.questionForm,
      [action.payload.prop]: action.payload.value 
    }
  };

This uses spread syntax along with computed property names (from ES6) to use an expression as an object key.

like image 115
Andrew Li Avatar answered Jan 05 '23 15:01

Andrew Li