Home > Net >  Why can't I check the checkbox?
Why can't I check the checkbox?

Time:06-28

I'm trying to implement a functionality that allows me to check a checkbox through the id. But when I try to check my checkbox, it doesn't show up as checked. I can't make an event, even using event.target. How can I resolve this?

import { useUsers } from '../../services/hooks/useUsers';

import {
  Box,
  Button,
  Checkbox,
  Flex,
  Heading,
  Icon,
  Table,
  Tbody,
  Td,
  Th,
  Thead,
  Tr,
  Text,
  useBreakpointValue,
  Spinner,
  Link,
  HStack,
  useDisclosure,
} from '@chakra-ui/react';
import { Header } from '../../components/Header';
import { NotificationModal } from '../../components/NotificationModal';
import { Sidebar } from '../../components/Sidebar';

import { RiAddLine } from 'react-icons/ri';
import { CgImport } from 'react-icons/cg';
import { TbEdit } from 'react-icons/tb';
import { FaWhatsapp } from 'react-icons/fa';
import { CgNotes } from 'react-icons/cg';

import { Pagination } from '../../components/Pagination';

import NextLink from 'next/link';
import { useEffect, useState } from 'react';
import { queryClient } from '../../services/queryClient';
import { api } from '../../services/api';

export default function UserList() {
  const [page, setPage] = useState(1);

  const { data, isLoading, isFetching, error } = useUsers(page);
  const [user, setUser] = useState([]);
  const [ids, setIds] = useState([]);

  useEffect(() => {
    if (data) {
      console.log(data)
      setUser(data.users);
    }
  }, [data]);

  function selectUser(e) {
    const selectedId = parseInt(e.target.value);

    if (ids.includes(selectedId)) {
      const newIds = ids.filter((id) => id !== selectedId);
      setIds(newIds);
    } else {
      const newIds = [...ids];
      newIds.push(selectedId);
      setIds(newIds);
    }
  }

  console.log({selectUser})

  async function handlePrefetchUser(userId: string) {
    await queryClient.prefetchQuery(
      ['user', userId],
      async () => {
        const response = await api.get(`users/${userId}`);

        return response.data;
      },
      {
        staleTime: 1000 * 60 * 10,
      }
    );
  }

  return (
    <Box>
      <Header />

      <Flex my="6" maxWidth={1480} mx="auto" px="6">
        <Sidebar />

        <Box flex="1" borderRadius={8} bg="gray.800" p="8">
          <Flex mb="8" justify="space-between" align="center">
            <Heading size="lg" fontWeight="normal">
              Alunos
              {!isLoading && isFetching && (
                <Spinner size="sm" color="gray.500" ml="4" />
              )}
            </Heading>

            <HStack spacing={4}>
              <NextLink href="/users/create" passHref>
                <Button as="a" size="sm" fontSize="sm" colorScheme="orange">
                  <Icon as={RiAddLine} fontSize="20" />
                </Button>
              </NextLink>

              <NotificationModal />

              <Button
                as="a"
                size="sm"
                fontSize="sm"
                colorScheme="green"
                cursor="pointer"
              >
                <Icon as={CgImport} />
              </Button>
            </HStack>
          </Flex>

          {isLoading ? (
            <Flex justify="center" align="center">
              <Spinner />
            </Flex>
          ) : error ? (
            <Flex justify="center">
              <Text>Falha ao obter dados dos usuários.</Text>
            </Flex>
          ) : (
            <>
              <Table colorScheme="whiteAlpha">
                <Thead>
                  <Tr>
                    <Th px={['4', '4', '6']} color="gray.300" w="8">
                      <Checkbox colorScheme="orange" />
                    </Th>

                    <Th>Usuários</Th>
                    <Th>Ações</Th>
                    <Th w="8"></Th>
                  </Tr>
                </Thead>

                <Tbody>
                  {data.users.map((user) => (
                    <Tr key={user.id}>
                      <Td px={['4', '4', '6']}>
                        <Checkbox
                          colorScheme="orange"
                          value={user.id}
                          onChange={selectUser}
                          isChecked={ids.includes(user.id) ? true : false}
                        />
                      </Td>

CodePudding user response:

Is user.id a number / string of a number eg "1"? because if not, parseInt will return NaN

Even if they are you probably dont need to use parseInt anyway

const selectedId = e.target.value;
  • Related