Sameer
Sameer

Reputation: 103

Updating state with nested array of objects

This is something also called as deep state update. Where I have to update nested state array.

I am implementing a simple redux application. Here I want to update the state which is nested array of object. My reducer function takes state, action. I have to update responses property of state with new value. I tried to map/iterate the state but it isnt working for me. Is there a way to update those specific values and return update state.

const sampleData = [{
  "id": 1,
  "text": "Hobby",
  "answers": [{
    "id": 1,
    "text": "Chess",
    "responses": 5
  }]
}];

const action = {
  type: "VOTE",
  questionId: 1,
  answerId: 3
};

This is handleSubmit function I am calling when Submit button is clicked on form.

handleSubmit(e){
  const store = createStore(hobbyReducer, hobby); // created store here
  var k = (document.querySelector('input[name = "hobby"]:checked').value);

  store.dispatch({type:"SUBMIT", text: k, id: 1});  // Dispatching action to reducer
  store.subscribe(()=>{

      console.log(store.getState());
  });
}

Here is reducer part of program:

function hobbyReducer(state, action) {
    switch(action.type){
      case "SUBMIT":
            return{
              ...state,
              answers: state.answers.map(e=> (e.text === action.text && e.answers.id === action.id)?
              { ...answers, 
              responses: (e.responses+1)} :
             hobby )
          }
      break;
      default:
        return state;
    }
}

initial state = sampleData; // Array object given above

I am unable to update the responses property which is in a nested array

This is the code I wanted to write, after some research I finally did what was required. Although this is not solution in terms of time complexity.

`

case "SUBMIT":
        const updatedState = state.map(e =>{
          if(e.id === action.id)
            return{...e,
                  answers: e.answers.map(f =>{
              if(f.text === action.text){
                return{
                  ...f,
                  ...{responses: f.responses + 1},

                }
              }
              return f;
            })
          }
        return e;
        })
        console.log("updatedstate", updatedState)
        return updatedState

Upvotes: 0

Views: 938

Answers (1)

Rick Jolly
Rick Jolly

Reputation: 3009

Just an error in your map I think:

 function hobbyReducer(state, action) {
    switch(action.type) {
      case "SUBMIT":
        return {
          ...state,
          answers: state.answers.map(answer => {
            if (answer.text === action.text && answer.id === action.id) {
              answer.response = answer.response + 1;
            }
            return answer;
          });
        }
      default:
        return state;
    }
}

Upvotes: 1

Related Questions