Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

240
Visualizações
Reactjs: how to keep a selected item state in the pagination? React-hooks

I would like to keep the coloring of the selected item in the state, however, when changing pages (Ex: from 1 to 2 and back to 1), it loses the coloring and as default states start as false, a request is sent to remove all items from the state in useEffect.

is filtering 10 items per page, and when I change pages, apparently the state resets and starts from scratch, even though there are selected items on the page.

Types

type ISkySelected = {
    id: string
}

interface ISkusProps {
    id: string
    description: string
    code_sap: string
    stock_pe: string
    stock_atc: string

    enableSku: boolean
    skusSelectedList: (selected: ISkySelected) => void
    removeSkuSelected: (selected: ISkySelected) => void
}
export function CardList ({ id, description, code_sap, stock_pe, stock_atc, enableSku, skusSelectedList, removeSkuSelected }: ISkusProps) {
  const [selected, setSelected] = useState<boolean>(false)
  const [color, setColor] = useState<string>('red.500')
  const [cursor, setCursor] = useState<string>('')

  function selectedSku (event: MouseEvent) {
    event.preventDefault()

    if (!enableSku) {
      return
    }

    setSelected(!selected)
  }

  useEffect(() => {
    if (selected) {
      setColor('red.500')
      skusSelectedList({ id: id })
    }

    if (!selected) {
      removeSkuSelected({ id: id })
      setColor('white')
    }
  }, [selected])

  useEffect(() => {
    if (enableSku) {
      setCursor('pointer')
    }

    if (!enableSku) {
      setSelected(false)
      setCursor('')
    }
  }, [enableSku])

   return (
    <Box
        cursor={cursor}
        borderRadius='2px'
        overflow='hidden'
        h='400px'
        w='225px'
        mt={5}
        borderWidth='4px'
        borderColor={color}
        onClick={(e) => selectedSku(e)}
    > ...myComponente </Box>
  )
})

PRINTS

selected an item: enter image description here

back one page: enter image description here

returning to the page that was: enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The problem is that when CardList is unmounted and remounted, the state of the component is reinitialized. You can store IDs array of selected cards higher up the tree. And then pass the selected prop to the card. For example like this:

interface CardProps {
  id: string;
  selected: boolean;
  toggleSelect: (id: string) => void;
}

const Card = ({ id, selected, toggleSelect }: CardProps) => {
  const [color, setColor] = useState<string>('red.500');

  const handleClick = () => {
    toggleSelect(id);
    setColor(selected ? 'red.500' : 'white');
  };

  return (
    <Box onClick={handleClick} color={color}>
      ...Component
    </Box>
  );
};

const List = () => {
  const [selectedIds, setSelectedIds] = useState<string[]>([]);

  const toggleCardSelected = (cardId: string) => {
    const isSelected = selectedIds.includes(cardId);
    if (isSelected) {
      setSelectedIds((prev) => prev.filter((id) => id !== cardId));
    } else {
      setSelectedIds((prev) => [...prev, cardId]);
    }
  };

  return (
    <>
      {cards.map(({ id }) => (
        <Card id={id} selected={selectedIds.includes(id)} toggleSelect={toggleCardSelected} />
      ))}
    </>
  );
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda