skip to Main Content

this my object

product: {
 variants:[
   {
    id:"my-key"
    metafields:[
       {
         value:{
           indexes:[
               1342332,
               2213213
             ]
          }
       }
     ]
   }
 ]
}

this is what I try to do

updateProduct: (state, action: PayloadAction<any>) => {
            const { id, key } = action.payload;

            if (state?.product?.variants) {
                const objectIndex = state?.product?.variants.findIndex(obj => obj.id === id);

                if (objectIndex !== -1) {
                    if (typeof state.product.variants[objectIndex]?.metafields !== undefined) {
                        state.product.variants[objectIndex]?.metafields?.forEach((item) => {
                            item.value.indexes.splice(Number(key));
                        });
                    }

                }
            }
        },

where id is "my-key" and the key is 1342332 and metafields is all ways [0],
but for some reason is not working I mean is not removing anything, I Have the same code that is working when I use push, please any help I am block on this thanks.

2

Answers


  1. Chosen as BEST ANSWER

    I found a solution as follows

            updateProduct: (state, action: PayloadAction<any>): any => {
                const { id, key } = action.payload;
    
                if (state?.product?.variants) {
                    const variant = state?.product?.variants.find(v => v.id === id);
                    if (variant?.metafields) {
                        variant?.metafields.forEach(metafield => {
                            const index = metafield.value.indexes.indexOf(key);
                            if (index !== -1) {
                                metafield.value.indexes.splice(index, 1);
                            }
                        });
                    }
                }
            }
        }
    

    this work for me.


  2. Since you are using Redux-Toolkit you can write a reducer function that directly mutates the draft state. Find first the specific variant by id, and if it exists and has a metafields array with a zeroth element then filter that element’s value.indexes array by the key.

    Example:

    updateProduct: (state, action: PayloadAction<any>) => {
      const { id, key } = action.payload;
    
      const variant = state.product?.variants?.find(variant => variant.id === id);
    
      if (variant?.metafields?.[0].value.indexes) {
        variant.metafields[0].value.indexes = variant.metafields[0].value.indexes.filter(
          field => String(field) !== key
        );
      }
    },
    

    It’s not clear how much of that state object is guaranteed to be defined so you may need to use more, or less, Optional Chaining operators depending on what is actually guaranteed to exist.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search