Home > other >  Updating array without mutating it
Updating array without mutating it

Time:02-21

From what I understand you should never mutate an object inside an array directly in react native, however say that I want to update a specific object inside an array - but still keep the same index nr and position of that object, selectedGoal in this case. How would I do that?

Now it keeps adding it to the end, which makes the item always appear in the end when it's manipulated.

const [goals, setGoals] = useState([])

...other code here...

    const updatedGoal = [...goals.filter(goal=>goal.id !== selectedGoal.id), selectedGoal]
    setGoals(updatedGoal)

example of nested array:

const addTodoToGoal = (todo, goalListId) =>{
    const relevantList = goals.find(list=> list.id === goalListId) 
    relevantList.todos.push(todo)                                  
    const goalsMinusRelevantList = goals.filter((list)=>list.id !== goalListId)  
    const newGoals=[...goalsMinusRelevantList, relevantList]
    setGoals(newGoals)

CodePudding user response:

Filtering with state:

const updatedGoal = goals.filter(item => item.id === id);
setGoals(updatedGoal);

You can use map instead and a if ternary to return the new object or the old one instead if you want to change something inside the list:

const updatedGoal = goals.map(item => item.id === id ? {} : item);
setGoals(updatedGoal);

You can also pass the new value directly inside the state:

setGoals(prev => prev.map(item => item.id === id ? {} : item));

Filtering with same logic:

setGoals(prev => prev.filter(item => item.id === id));

EDIT

In your code case, your are filtering the the goals that not match the id and putting the selectedGoal at the end of the list:

const updatedGoal = [...goals.filter(goal=>goal.id !== selectedGoal.id), selectedGoal]

If you want to update a specific item you should try the map keyword like my example, inside the map you can match the selectedId and change the object, something like this:

const updatedGoal = goals.map(item => item.id === selectedGoal.id
? ({
   ...item, // this keep attributes you dont want to change
   done: true, // here you can change other attributes
   foo: "bar",
  })
: item);

  • Related