1

I want to change the id of a specific element inside my array. I tried to clone the array and then changed the id but the original array has changed too.

const initialState = {
transactions: [

],
items: [
    { id: 1, text: 'Flower', amount: 20 , discount:2},
    { id: 2, text: 'Ps4', amount: 300, discount:1 },
    { id: 3, text: 'Book', amount: 10, discount:0 },
    { id: 4, text: 'Camera', amount: 150 , discount:3}

]}


const reducer = (state, action) => {
switch (action.type) {
    case "ADD_TRANSACTION":
        const clonedItems = [...state.items]
        const randomNum = Math.floor((Math.random() * 1000000));
        clonedItems[action.payload-1].id = randomNum
        return {
            ...state,
            
            transactions: [clonedItems[randomNum], ...state.transactions]
            
        }

action.payload is index of the element that I want to change.

RealAlpha
  • 21
  • 1
  • 6
  • Does this answer your question? [Whats the best way to update an object in an array in ReactJS?](https://stackoverflow.com/questions/28121272/whats-the-best-way-to-update-an-object-in-an-array-in-reactjs) – Emile Bergeron Nov 02 '20 at 18:30

1 Answers1

3

You're cloning the array, but not the inner object - you're mutating the state object, which is the problem.

Change

clonedItems[action.payload-1].id = randomNum

to

clonedItems[action.payload-1] = {
  ...clonedItems[action.payload-1],
  id: randomNum
};
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320