Home > Mobile >  OnClick Button keeps rerendering in React after mapping
OnClick Button keeps rerendering in React after mapping

Time:11-17

New to react so any help would be appreciated! I have a table of users that I've mapped out from an API call. I also needed an Edit button so I could edit a user in a separate form. But when I pass the object into my handleEditShow function on the onclick function of that edit button, I get an error: "Too many re-renders. React limits the number of renders to prevent an infinite loop."

 const [showEdit, setShowEdit] = useState(false);
    
    const handleEditShow = (user) => {
      console.log(user);
      setShowEdit(true);
       setEditUser({person: "" })
    };
    const handleEditClose = () => setShowEdit(false);
    
    const [editUser, setEditUser] = useState({userEdit:[]});

My plan was to set the edited user into its own state and then pass that into a different component(form in a modal).

<Table striped>
      <thead>
        <tr>
          <th>Name</th>
          <th>Login</th>
          <th>Last Active</th>
          <th>Email</th>
          <th>Supervisor</th>
          <th>Active</th>
          <th>Language</th>
          <th>Edit</th>
        </tr>
      </thead>
      <tbody>
        {
            users.person && users.person.map((item)=>(
            <tr key={item.id}>
              <td>{item.name}</td>
              <td>{item.login}</td>
              <td>{item.lastActive}</td>
              <td>{item.email}</td>
              <td>{item.supervisor}</td>
              <td>{item.active}</td>
              <td>{item.language}</td>
              <td><Button variant="secondary" id={item.id} onClick={handleEditShow(item)}>
                  Edit
                </Button>
              </td>
            </tr>
            ))
        }
      </tbody>

I was thinking of passing the user that needs to be edited like this:

<Modal show={showEdit} onHide={handleEditClose}>
        <Modal.Header closeButton>
          <Modal.Title>User Editor</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <EditForm user={editUser} />
        </Modal.Body>
        <Modal.Footer>
        </Modal.Footer>
      </Modal>

CodePudding user response:

try onClick={()=>handleEditShow(item)} instead onClick={handleEditShow(item)}

The reason is, the state immediately changes when the component is rendered and it causes a rerendering, infinite loop.

CodePudding user response:

Change this:

const handleEditShow = (user) => {
  console.log(user);
  setShowEdit(true);
  setEditUser({person: "" })
};

to this:

const handleEditShow = (e) => (user) => {
  console.log(user);
  setShowEdit(true);
  setEditUser({person: "" })
};

That's because your function is getting invoked on mount since you're calling it with braces, ie, you're doing:

onClick={handleEditShow(item)}
  • Related