How do I add an element to array in reducer of React native redux?

coderzzz18 picture coderzzz18 · Dec 1, 2016 · Viewed 135.2k times · Source

How do I add elements in my array arr[] of redux state in reducer? I am doing this-

import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {
    arr:[]
}

export default function userState(state = initialUserState, action)
{
    console.log(arr);
    switch (action.type)
    {
        case ADD_ITEM: 
            return { 
                      ...state,
                      arr: state.arr.push([action.newItem])
                   }

        default:
            return state
    }
}

Answer

Yadhu Kiran picture Yadhu Kiran · Dec 2, 2016

Two different options to add item to an array without mutation

case ADD_ITEM :
    return { 
        ...state,
        arr: [...state.arr, action.newItem]
    }

OR

case ADD_ITEM :
    return { 
        ...state,
        arr: state.arr.concat(action.newItem)
    }