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
I found a solution as follows
this work for me.
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’svalue.indexes
array by thekey
.Example:
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.