Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating array without changing its order

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading