Search code examples
javascriptreactjsmaterialize

React, when using materialize modal => deletes item with wrong _id


I have two components. When click on trash icon in component UserItem - modal DeleteUserModal shows with confirm button "delete".
But when I delete item - it deletes the wrong item... Using onMouseOver={() => console.log(_id)} in modal component on different items, I can see, that _id is not changing, but why?

By the way, if I use onDelete function directly in UserItem component - it works fine.

const UserItem = ({ user, index }) => {
  const userContext = useContext(UserContext);
  const { setIndexUser, deleteUser } = userContext;
  const { firstName, lastName, role, _id } = user;
  const onDelete = () => {
    setIndexUser(null);
    deleteUser(_id);
  };
  useEffect(() => {
    M.AutoInit();
    // eslint-disable-next-line
  }, []);
  return (
    <div className="card">
      <div
        className="right-align card-action"
        onMouseOver={() => console.log(_id)}
      >
        {" "}
        // works fine, shows id of howered item
        <a href="#delete-user-modal" className="modal-trigger">
          <i className="fas fa-trash-alt" />
        </a>
      </div>
      <DeleteUserModal onDelete={onDelete} _id={_id} />
    </div>
  );
};

Modal to delete item:

import React from "react";

const DeleteUserModal = ({ onDelete, _id }) => {
  return (
    <div id="delete-user-modal" className="modal">
      <div className="modal-content">
        <h4>Delete this user, all his RCOMs and devices?</h4>
      </div>
      <div className="modal-footer" onMouseOver={() => console.log(_id)}>
        {" "}
        //works incorrectly, id sticks the same...
        <a
          href="#!"
          className="modal-close waves-effect waves-green btn-flat red-text"
          onClick={onDelete}
        >
          Delete
        </a>
      </div>
    </div>
  );
};
export default DeleteUserModal;


Solution

  • I've solved this issue using Context API: when trash icon clicked - _id is saving to the store. And then it is passed to the modal. In this case it works correctly.