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

323
Vistas
Cities aren't sorting on user click

I have a prop that's an array of objects and I'm trying to sortBy different fields like id, city, etc. For some reason my state isn't changing on the DOM but when I do a console.log it changes. I'm using react hooks and sort as the key for which I want to sort the fields

import { useEffect } from 'react'
import { useState, useCallback } from 'react'
import type { City } from 'api/getCities';
import SortableTableColumnHeader from './SortableTableColumnHeader';
import SortableTableCell from './SortableTableCell';
import s from './SortableTable.module.css'

interface CityProps { cities: City[] }

export default function SortableTable(props: CityProps): JSX.Element {
  const { cities } = props
  const [formattedCities, setFormattedCities] = useState<City[]>(cities)
  const [sort, setSort] = useState<string>('')

  useEffect(() => {
    if (sort === 'id') {
      const formattedById = cities.sort((a, b) => a.id - b.id)
      setFormattedCities(formattedById)
    }
    else {
      setFormattedCities(cities)
    }
    console.log(sort)
  }, [cities, sort]);

  const handleClick = useCallback((id: string, iso: string, city: string, capital: string, population: string, country: string) => {
    if (id) {
      setSort('id')
      // const formattedById = id === 'ASC' ? cities.sort((a, b) => a.id - b.id) : cities.sort((a, b) => b.id - a.id).reverse()
    }

  }, [])


  return (
    <div role="table" className={s.table}>
      <div role="rowgroup" className={s.thead}>
        <SortableTableColumnHeader onClick={handleClick} />
      </div>
      <div role="rowgroup" className={s.tbody}>
        {formattedCities.map((city) => {
          return <SortableTableCell key={city.id} {...city} />
        })}
        {/* {formattedCities.length ? formattedCities.map((city) => {
          return <SortableTableCell key={city.id} {...city} />
        }) : cities.map((city) => {
          return <SortableTableCell key={city.id} {...city} />
        })} */}
      </div>
    </div>
  )
}
about 4 years ago · Juan Pablo Isaza
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