Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

325
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!