mercredi 3 mai 2017

Changing local value in function, modifies global state in react

I have react component with a array of a shoppinglist in state. The shoppinglist have multiple arrays and object to reflect which ingredients matches each day and meal.

This functions loops through each ingredient push it to an empty array which I later maps over and returns the value. When I find an ingredient which already exists in the ingredient-array, then it modifies the value instead of pushing a new similar ingredient. (the reason for this is that a breakfast on monday and tuesday can both have the ingredient "apple", and then I just want to show "apple" in the list once, but have the amount of values to reflect both breakfasts.

The problem: The value of the ingredient I modify is changed on state-level. Which means when I run the function again (I do because the user can filter days) the value increases.

Scenario Breakfast in both monday and tuesday has the ingredient Apple. Apple has a value of 2, since the recipe needs two apple. This means my loop should return 4 apples. And it does the first time. But when I change som filters so the loops run again to reflect the new filter, it now shows 6 apples.

Can someone tell me how this is possible? How can this code modify my global state?

loopIngredients (items) {
    const ingredients = []
    const newArr = items.slice()

    newArr.map((data, key) => {
      data.map((data, index) => {
        const valid = ingredients.find((item) => item.ingredient.id === data.ingredient.id)
        if (valid) {
          const parentValue = parseInt(ingredients[index].value)
          const localValue = parseInt(data.value)
          ingredients[index].value = (parentValue + localValue).toString()
        } else {
          ingredients.push(data)
        }
      })
   })
} // END loopIngredients

Aucun commentaire:

Enregistrer un commentaire