Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Emokores's avatar

Array.map() interfering with modal state - Inertia with React

I have two buttons in a datatable that trigger two different modal dialogs to open show and delete. Everything worked fine until I added a function to display an array of data in one of the modals and every time I try to open the other modal I get the error: Uncaught TypeError: Cannot read properties of undefined (reading 'map'). My code breaks. Here's the code:

const [confirm, setConfirm] = useState(false), [showData, setShowData] = useState(false);

<Modal open={showData} setOpen={setShowData}>
    {/* To show user data from the datatable */}
    <div>
          {task.assignees.map((assignee) => {
                return (
                    //List of assignees to a task
                 );
           })}
    </div>
</Modal>

<ModalDialog open={confirm} setOpen={setConfirm}>
    {/* To delete user data from the datatable */}
</ModalDialog>

I tried shifting my delete-modal to the Edit.js page and still the code breaks. I get the error: Uncaught TypeError: Cannot read properties of undefined (reading 'includes'). How can I display the delete-modal with the arrays on the page?

0 likes
5 replies
Sinnbeck's avatar

Make sure to return early if task is empty

if (! task || ! task.assignees.length ) {
    return null
}

Or only do the map if task is available

{task && task.assignees.length ? task.assignees.map((assignee) => {
                return (
                    //List of assignees to a task
                 );
           }) : null}
1 like
Sinnbeck's avatar

You can also reassign it to something you control

const assignees = task && task.assignees.length ? task.assignees : []
1 like
Emokores's avatar

@Sinnbeck thanks so much for replying. I have been trying some debugging. Generally, I am passing some data to the modal so that it is more interactive. The heading is like Delete {this} record? and the body of the modal has You are trying to delete {this}. Are you sure? so I'm passing {this} data to the modal as setTask({task_name: task.task_name}), but because of the array.map() in the other modal, this piece of data becomes undefined. I think I need a better way of passing the data.

Sinnbeck's avatar

@Emokores you can just return null as in the first example if it only gets set when state updates

1 like
Emokores's avatar
Emokores
OP
Best Answer
Level 2

@Sinnbeck Wow! After shifting my modal to the Edit.js page from Index.js, I simply removed the setTask({task_name: task.task_name}) from the button and the function worked. Everything works, though I needed to capture the error as you've said. Thanks a lot.

Please or to participate in this conversation.