Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

250
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda