javascript - Redux - Having an issue concatenating new state when an Item is added to an array -
currently having issue reducer function not update questionlist.items
array. i'm not sure i'm doing wrong here awesome if point me in right direction :)
below snippet of code i'm having issue with. problem lies add_questions
action it not concatenate existing items in array new item. instead, it overwrites existing item in array.
const add_question = 'add_question'; const fetch_questions = 'fetch_questions'; const fetch_questions_success = 'fetch_questions_success'; const fetch_questions_failure = 'fetch_questions_failure'; const initial_state = { questionslist: {items: [{ id: 2222, questionstring: 'your name', rejected: true }], error:null, loading: false}, newquestion:{question:null, error: null, loading: false}, activequestion:{question:null, error:null, loading: false}, deletedquestion: {question: null, error:null, loading: false}, }; const questionsreducer = (state = initial_state, action) => { const { payload, type } = action; switch (type) { case fetch_questions: return { ...state, questionslist: {items:[], error: null, loading: true} }; case fetch_questions_success: return { ...state, questionslist: {items: action.payload, error:null, loading: false} }; case add_question: /** problem lies here */ return { ...state, questionslist: { items: [...state, payload], error: null, loading: false } } default: return state } } export default questionsreducer;
i've taken screenshot of redux devtools console better show issue i'm dealing with. taking @ picture below see initial item in items
array gets replaced when add_question
fires.
you trying spread whole state
, not list of questions:
return { ...state, questionslist: { items: [...state, payload], error: null, loading: false } }
you cannot spread object array. instead, only spread relevant slice of state:
return { ...state, questionslist: { items: [...state.questionslist.items, payload], error: null, loading: false } }
Comments
Post a Comment