mercredi 19 janvier 2022

React Checkbox is unchecked when there is a search input

I made a selectable and searchable popup list.

After I searched and selected names like the screenshot below

enter image description here

and open the popup again, searched with the same word or words contained in the selected usernames. The checkbox were uncheck and selectable, thus leading to duplicates.

enter image description here

**If I erase the word from search bar, the check box are checked.

enter image description here

Is there any way I can fix so that the selected will always remain selected?

Appreciate all your helps.

UserList.tsx

export const UserList = (props: {
    showsUserList: boolean; handleClose: () => void; corporationId: string; currentUserId: string; samePerson: boolean; twj: string;
  }) => {
    const handleOnMemberClicked = (checked: boolean, userId: string | null) => {
    const newList = addedUserList;
    const index = userList.findIndex((user) => user.userId == userId);

    if (checked) {
      newList.push({ userId: userList[index].userId, name: userList[index].name });
      setCount(count + 1);
    } else {
      for (let i = 0; i < newList.length; i++) {
        if (newList[i].userId == userId) {
          newList.splice(i, 1);
          break;
        }
      }
      setCount(count - 1);
    }
    setAddedUserList(newList);
  };
  useUserList(corporationId, props.twj)
  useAddUserList(addedUserList);
  const searchUserOnClick = (e: ChangeEvent<HTMLInputElement>) => {
    setUserName(e.target.value);
  };

  const searchedUserList = useMemo(() => {
    if (!userList) {
      return [];
    }
    let filteredUserList = userList
      .filter((user) => user.userId)
      .filter(({ userId, name }) => ({
        userId,
        name,
      }));
    if (props.isThePerson) {
      filteredUserList = filteredUserList.filter((user) => user.userId !== props.currentUserId);
    }

    if (addedUserList) {
      filteredUserList = filteredUserList.filter(
        (user) => !addedUserList.some((addedIds) => user.userId === addedIds.userId),
      );
    }

    return filteredUserList;
  }, [userList]);
    ......
    return ( <
      > <div className="reservation-popup-details scrollable">
            <ul className={`option-module-list no-list option-module-list-member ${style.personListMember}`}>
              {searchedUserList.map((user, i) => (
                <UserListElement user={user} handleOnMemberClicked={handleOnMemberClicked} isReset={isReset} key={i} />
              ))}
            </ul>
      .....
      </div>
    }

UserListElement.tsx

export const UserListElement = ({ user, handleOnMemberClicked, isReset,
}: { user: UserEntity;
  handleOnMemberClicked: (checked: boolean, userId: string | null) => void;
  isReset: boolean;
}) => {
  const [checked, setChecked] = useState(false);
  const addedUserIds = addedUserList.map((item) => item.userId) || [];
  const handleOnChange = (e: ChangeEvent<HTMLInputElement>) => {
    const checkedState = e.target.checked;
    setChecked(checkedState);
    handleOnMemberClicked(checkedState, user.userId);
  };
  useEffect(() => {
    setChecked(false);
  }, [isReset, user]);
  return (
    <li>
      <label className={style.checkboxLabel}>
        <input type="checkbox" className={style.checkboxCircle} 
           checked={checked || isCheck} onChange={(e) => handleOnChange(e)} />
        <span>{user.name}</span>
      </label>
    </li>
  );
};

UseAddUserList.tsx

export class UserDetail {
  constructor(public userId: string | null, public name: string | null) {}
}

export let addedUserList: UserDetail[] = [];
export let setAddedUserList: Dispatch<SetStateAction<UserDetail[]>>;

export const useAddUserList = (idList: UserDetail[]) => {
  [addedUserList, setAddedUserList] = useState(idList);
};

useUserList.ts

export const useUserList = (corporationId: string, jwt: string) => {
  [selectedUserName, setSelectedUserName] = useState(ALL_USERS);
  [userName, setUserName] = useState('');
  [userList, setUserList] = useState(INITIAL_USER_LIST);
  useAsync(
    async () =>
      setUserList([
        ...INITIAL_USER_LIST,
        ...(decideToGoToErrorPage(
          await CustomerListApi.search({ corporationId, userName, currentPageNo, displayCount }, jwt),
        )[1]?.map((user) => new UserEntity(user.userId ?? '', user.name ?? '', user.post ?? '')) ?? []),
      ]),
    [userName],
  );
};



Aucun commentaire:

Enregistrer un commentaire