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>
)
}