The edge case of an array map and react key

Vaibhav Rai
2 min readJan 10, 2021

Suppose there are patients in your clinic and they are waiting for their chance for a checkup and your internal dashboard for admins adding a capability to perform actions like adding doctor to a specific checkup or marking it done and you decided to show it in the table where a row of that table is a specific checkup and when checkup is done it will be removed from the table.

Now you added a modal (with help of react-modal) as a button in every row so that admins can perform inside the modal and you did all the above by passing the modal button as a row data.

How code will look like?

  • You are passing the columns name of the table, e.g.,
const columns = [{header: 'user_name', name: 'User name', { header: 'edit_checkup', name: 'Edit checkup'}]
  • You are passing rows data as an array of the dictionary to the table utility e.g.,
const tableData = chekups.map((checkup) => ({
user_name: checkup.user,
edit_reply: <CheckupModal checkup={checkup} />
}))

Issues in the code?

  • Bad code for thousands of checkups, on any actions (like adding a doctor) you re-rendering the unnecessary modal component for the whole table.
  • Major issue — “We didn’t attach any key to the CheckupModal”, inside the opened model whenever the admin performs an operation like marking the checkup as done, the behavior has to save the data first then close the modal.
    But saving is an async operation so there can be a case where checkup gets removed from the table and then closing action gets performed and if that is the case then we will have an issue where modal will remain open, why?
    index 0 gets removed and index 1 row data came to index 0 now react performed diff check and it said there is no change, it mutated the CheckupModal and modal remained open

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response