0

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?

1
  • Please share us your reducer and actions, if not im pretty sure it will be closed Commented Jun 5, 2018 at 7:26

3 Answers 3

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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']

1 Comment

push, unshift and splice are mutative function and should be avoided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.