Repeatedly showing this problem...
const reducer = (state, action) => {
switch (action.type) {
case "questions":
action.value.forEach(question => {
question.options.forEach(option => {
option.checked = false
})
})
return action.value
case "answer":
const questions = _.cloneDeep(state)
questions[action.questionID].options[action.optionIndex].checked =
action.value
return questions
default:
return state
}
}
CodePudding user response:
Try this
const reducer = (state, action) => {
switch (action.type) {
case "questions":
(action.value || []).forEach(question => {
(question.options || []).forEach(option => {
option.checked = false
})
})
return action.value
case "answer":
const questions = _.cloneDeep(state)
questions[action.questionID].options[action.optionIndex].checked =
action.value
return questions
default:
return state
}
}
CodePudding user response:
First, you have to check if the value exists or not in action.value
const reducer = (state, action) => {
switch (action.type) {
case "questions":
if(action && action.value && action.value.length){
action.value.forEach(question => {
question.options.forEach(option => {
option.checked = false
})
})
return action.value
}
case "answer":
const questions = _.cloneDeep(state)
questions[action.questionID].options[action.optionIndex].checked =
action.value
return questions
default:
return state
}
}
If you are using forEach then array should have length.
if(action && action.value && action.value.length){
action.value.forEach(question => console.log(question))
}