Checkboxes in dynamic Table

Hi,
I am building an app to display users in Dynamic table with checkbox for selection of each user.

everything is working fine as per my requirement but only challenge which i am facing is checkbox is not getting checked when i select the user.

below is the code for my Allusers.jsx

import React, { useEffect, useState, useCallback } from "react";
import { Checkbox, Stack, Inline, Text } from "@forge/react";
import { DTable, ButtonDanger, ButtonPrimary } from "./Components";
import { deleteUsers, getOrgUsers } from "./apiCalls";
import { sUserHead } from "./Heads";
import ModelForm from "./ModalForm";

export const AllUsers = () => {
  const [iUserRows, setIUserRows] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isDisabled, setIsDisabled] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const [dUserList, setDUserList] = useState([]);
  const [checkedUsers, setCheckedUsers] = useState({});

  const openModal = () => setIsModalOpen(true);
  const closeModal = () => setIsModalOpen(false);

  const deleteUser = useCallback(() => {
    if (dUserList.length > 0) {
      deleteUsers(dUserList).then((response) => {
        console.log(`delResp:${JSON.stringify(response)}`);
        if (response?.success) {
          setDUserList([]);
          setCheckedUsers({});
          fetchUsers(); // Refetch users to reset state after deletion
        }
      });
    }
  }, [dUserList]);

  const onCheckChange = (e) => {
    const { checked, value } = e.target;

    setDUserList((prevList) => {
      const isSelected = prevList.some((user) => user.accountId === value);

      const updatedList = isSelected
        ? prevList.filter((user) => user.accountId !== value)
        : [...prevList, { accountId: value }];

      setIsDisabled(updatedList.length === 0);
      console.info(`uList: ${JSON.stringify(updatedList)}`);

      return updatedList;
    });
    setCheckedUsers((prevCheckedUsers) => ({
      ...prevCheckedUsers,
      [value]: checked,
    }));
  };

  const fetchUsers = useCallback(() => {
    setIsLoading(true);
    getOrgUsers().then((users) => {
      if (users) {
        const userRows = users.map((user, index) => ({
          key: `${user.name}-user-${index}`,
          cells: [
            {
              key: `${user.name}-${index}`,
              content: (
                <Checkbox
                  value={user.accountId}
                  label={user.name}
                  defaultChecked={false}
                  checked={!!checkedUsers[user.accountId]}
                  onChange={onCheckChange}
                />
              ),
            },
            {
              key: `${user.email}-${index}`,
              content: <Text>{user.email}</Text>,
            },
            {
              key: `${user.isManaged}-${index}`,
              content: <Text>{user.isManaged}</Text>,
            },
            {
              key: `${user.last_active}-${index}`,
              content: <Text>{user.last_active}</Text>,
            },
            {
              key: `${user.status}-${index}`,
              content: <Text>{user.status}</Text>,
            },
            {
              key: `${user.activeDays}-${index}`,
              content: <Text>{user.activeDays}</Text>,
            },
          ],
        }));
        setIUserRows(userRows);
      }
      setIsLoading(false);
    });
  }, [checkedUsers]);

  useEffect(() => {
    fetchUsers();
  }, []);

  return (
    <Stack>
      <DTable
        head={sUserHead}
        rows={iUserRows || "Loading...."}
        rowsPerPage={10}
        isLoading={isLoading}
        totalCount={iUserRows.length}
        type="Users"
        defaultSortKey="name"
      />
      <Inline space="space.100">
        <ButtonDanger
          text="Delete"
          iconBefore="trash"
          onClick={deleteUser}
          isDisabled={isDisabled}
        />
        {/* <ButtonPrimary
          text="Change Email"
          iconBefore="file"
          onClick={openModal}
          isDisabled={isDisabled}
        /> */}
      </Inline>
      {isModalOpen && <ModelForm onClose={closeModal} userData={dUserList} />}
    </Stack>
  );
};

note sure where i am making mistake. i am struggling to resolve this since long time.
any help is much appreciated.

below is the output which i am getting

Thanks & Regards
Bhaskar

Hi @BhaskarWunnava

It sounds like your data that populates the checkbox state (checked or not) is not being updated correctly.

This ToDo app uses checkboxes in a dynamic table, please take a look at the source code GitHub - meliaecodes/jira-todo-uikit: A To Do List app for Jira built with Forge UI Kit and see if that helps.

If this helps you solve the issue, please do mark this as the solution.

Let me know if you have any questions!
Mel