R
R
Roma2021-06-11 20:57:57
React
Roma, 2021-06-11 20:57:57

Why are the columns not sorted, where is the error?

const useSortableData = (items, config = null) => {
    const [sortConfig, setSortConfig] = React.useState(config);
  
    const sortedItems = React.useMemo(() => {
      let sortableItems = [...items];
      if (sortConfig !== null) {
        sortableItems.sort((a, b) => {
          if (a[sortConfig.key] < b[sortConfig.key]) {
            return sortConfig.direction === 'ascending' ? -1 : 1;
          }
          if (a[sortConfig.key] > b[sortConfig.key]) {
            return sortConfig.direction === 'ascending' ? 1 : -1;
          }
          return 0;
        });
      }
      return sortableItems;
    }, [items, sortConfig]);
  
    const requestSort = (key) => {
      let direction = 'ascending';
      if (
        sortConfig &&
        sortConfig.key === key &&
        sortConfig.direction === 'ascending'
      ) {
        direction = 'descending';
      }
      setSortConfig({ key, direction });
    };
  
    return { items: sortedItems, requestSort, sortConfig };
  };


const Countries = ({data}) => {    
    const [showCard, setShowCard] = useState('none');
    const { items, requestSort, sortConfig } = useSortableData(data);

    const ShowOnClick = (cardId) =>{
        setShowCard(cardId)
    } 

    const CloseOnClick = (e) => {
        e.stopPropagation();
        setShowCard('none')
    }  
    
    const getClassNamesFor = (country) => {
        if (!sortConfig) {
          return;
        }
        return sortConfig.key === country ? sortConfig.direction : undefined;
      };
 
    return (
    <table className="table">
        <thead>
            <tr>
                <th onClick={() => requestSort('№')}
                    className={getClassNamesFor('№')}>№</th>
                <th onClick={() => requestSort('country')}
                    className={getClassNamesFor('country')}>Country</th>
                <th onClick={() => requestSort('Total Confirmed')}
                    className={getClassNamesFor('Total Confirmed')}>Total Confirmed</th>
            </tr>
        </thead>
        <tbody>
            {items.map((country, index) => (                        
                <tr onClick={() => ShowOnClick(index)} key={index}>
                    <td>{index + 1}</td>
                    <td>{country.Country}</td>
                    <td>{country.TotalConfirmed}</td>                     
                </tr>
            ))}
        </tbody>
    </table>
    )
};

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question