I am trying to reproduce my original problem.
I have two arrays in react state, and Array1 is the original array from Database and Array2 is the updated array in state.
The objective is to update only changed rate and not quantity (and other properties) back to the Database, hence i need to update the values of rates in object of basicrecipe with the values of the rates in object of recipeBasicRecipe array for a the objects of basicrecipe matching with the objects in recipeBasicRecipe.
I am getting this error when I run the code, request help
Error:Uncaught TypeError: Cannot assign to read only property
let basicRecipes = [
{
id: 1,
name: IceCream,
details: [{ id: "12", name: "milk", quantity: "50", rate: "100" },
{ id: "13", name: "cream", quantity: "50", rate: "300" }]
},
{
id: 2,
name: Coffee,
details: [{ id: "14", name: "Coffee bean", quantity: "60", rate: "200" },
{ id: "15", name: "water", quantity: "60", rate: "300" }]
},
{
id: 3,
name: Tea,
details: [{ id: "16", name: "Tea leaf", quantity: "50", rate: "700"
}]
}]
let recipeBasicRecipe = [
{
id: 1,
name: IceCream,
details: [{ id: "12", name: "milk", quantity: "50", rate: "500" },
{ id: "13", name: "cream", quantity: "50", rate: "700" }]
},
{
id: 2,
name: Coffee,
details: [{ id: "14", name: "Coffee bean", quantity: "60", rate: "800" },
{ id: "15", name: "water", quantity: "60", rate: "8000" }]
}
];
let r = basicRecipe;
let Array2 = recipeBasicRecipes;
r = r.map(item => {
let element = Array2.find(e => e.id == item.id);
if (element) {
item.details = item.details.map(e => {
let detail = element.details.find(d => d.id == e.id);
if (detail) {
e.rate = detail.rate;
}
return e;
});
}
return item;
});
console.log(r);
const initialState = {
basicRecipe: [],
recipeBasicRecipes: [],
};
const [state, dispatch] = useReducer(recipeManagementReducer, initialState);
Function where I am executing this code
const onSubmit = e => {
e.preventDefault();
/**
*
setShowLoader();
updateawMateris(state.recipeRawMaterials);
* */
let r = state.basicRecipe;
let Array2 = state.recipeBasicRecipes;
r = r.map(item => {
let element = Array2.find(e => e._id == item._id);
if (element) {
item.details = item.details.map(e => {
let detail = element.details.find(d => d._id == e._id);
if (detail) {
e.rate = detail.rate;
}
return e;
});
}
return item;
});
While playing around I changed the return to make it immutable as that was cause of the errors.
Here is the snippet, only problem is this returns change on Quantity in recipe as well, how do I avoid that
let r = [...state.basicRecipe];
let Array2 = [...state.recipeBasicRecipes];
r = r.map(item => {
let element = Array2.find(e => e._id === item._id);
if (element) {
item.details = item.details.map(e => {
let detail = element.details.find(d => d._id === e._id);
if (detail) {
return {
...e,
rate: detail.rate
};
}
return e;
});
}
return item;
});
console.log(r);