Shashika Virajh
Shashika Virajh

Reputation: 9457

Adding an object to array in redux with the index

I want to add a new object to an array which is in redux in my react native application. I used splice and it did not work. What is the preferred way to insert items using index in redux?

Upvotes: 0

Views: 1651

Answers (3)

pritesh
pritesh

Reputation: 2192

There are various ways you can do it.But you should avoid using methods such as push, unshift, splice as these mutate the state which is against the react philosophy.You can check this link for more information on how to update redux store.

You can use

function insertItem(array, action) {
    return [
        ...array.slice(0, action.index),
        action.item,
        ...array.slice(action.index)
    ]
}

So from the reducer if suppose your(not sure how your reducer is defined) you can call

return {...state, array: insertItem(state.array, action)}

Considering the item need to be inserted into the array property.

If you want to use splice anyway then you need to clone the array using slice and then mutate the cloned array like:

function insertItem(array, action) {
    let newArray = array.slice(); //Returns new array
    newArray.splice(action.index, 0, action.item);
    return newArray;
}

Upvotes: 3

GauthierG
GauthierG

Reputation: 308

splice is supposed to work. Can you show us your code please ?

Do you use it like this ? :

var months = ['Jan', 'March', 'April', 'June'];

months.splice(1, 0, 'Feb'); 
// inserts at 1st index position
console.log(months); 
// expected output: Array ['Jan', 'Feb', 'March','April', 'June']

months.splice(4, 1, 'May'); 
// replaces 1 element at 4th index
console.log(months); 
// expected output: Array ['Jan', 'Feb', 'March','April', 'May']

Upvotes: 0

aravind_reddy
aravind_reddy

Reputation: 5466

If you want to add new object to an array at a particular index without mutating the array you can use Object.assign:

Object.assign([], array, {<position_here>: newItem});

if you have 2 elements and add an object at index 3 instead of 2 you will have undefined at index 2

Upvotes: 1

Related Questions