Mapping over array items doesn't render all elements

after I update an answer in my object it becomes undefined. So it doesn't fit the rest of my application, what I have in the begginging:

0
:
{answers: Array(5), category: {…}, description: null, legacyName: null, name: null, …}
1
:
{answers: Array(3), category: {…}, description: null, legacyName: null, name: null, …}
2
:
{answers: Array(3), category: {…}, description: null, legacyName: null, name: null, …}
3
:
{answers: Array(3), category: {…}, description: null, legacyName: null, name: null, …}
4
:
{answers: Array(2), category: {…}, description: null, legacyName: null, name: null, …}

what I have after the change:

0
:
undefined
1
:
undefined
2
:
undefined
3
:
undefined
4
:
undefined

The reducer:

function updateObject(oldObject, newValues) {
  return Object.assign({}, oldObject, newValues);
}

function updateItemInArray(array, questionId,answerId, newValue) {
  return {
    project: array.map(item => {
      if(item.id !== questionId) {
        return item;
      } else {
        item.answers.map(answer => {
          if(answer.id !== answerId) {
            return answer;
          } else {
            updateObject(answer, { value : newValue})
          }
        });
      }
    })
  }
}


export function project(state = [], action){

  switch(action.type){
    case 'PROJECT_FETCH_SUCCESS':
      return action.project; //initialize the project from a fetch
    case 'ANSWER_UPDATE_SUCCESS':
    {
      return updateItemInArray(state, action.questionId, action.answerId, action.newValue); //Want to change a value in one object in the array of arrays
    }
    default:
      return state
  }
}

What I want to do is to find the array in the array and then find the object in that array to change it's value. But for some reason it returns undefined. The functions that I'm using I saw in the redux documentation: https://redux.js.org/recipes/structuring-reducers/refactoring-reducers-example

Answers:

Answer

You are not returning from the else condition inside the map function

function updateItemInArray(array, questionId,answerId, newValue) {
  return {
    project: array.map(item => {
      if(item.id !== questionId) {
        return item;
      } else {
        // need a return statement here
        return item.answers.map(answer => {
          if(answer.id !== answerId) {
            return answer;
          } else {
            updateObject(answer, { value : newValue})
          }
        });
      }
    })
  }
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.