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.

1

1 Answer 1

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

Comments

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.