title: React js: How to sort item from API data by ascending and descending
body: <p>I am fetching data <strong>from</strong> an <strong>API</strong>, which includes information about <strong>countries</strong>. I want to sort the countries by ascending and descending from <strong>onClick</strong> according their names. For now the order of name's output is in <strong>alphabetical</strong> order(A-Z). I want to sort it to <strong>Z-A</strong> from onClick in the <strong>name</strong> in <strong>Header</strong> component. <br>
  Any help will be appreciated.</p>
  <p>Here isthe component I'm fetching data: useCountries</p>
  <pre><code>
  import { useState, useEffect } from 'react'
  
  export default function useCountries(search: string) {
    const [data, setData] = useState([])
    const [savedCountries, setSavedCountries] = useState([])
    const fetchData = () =&gt; {
      fetch('https://restcountries.eu/rest/v2/all')
        .then((res) =&gt; res.json())
        .then((result) =&gt; {
          setData(result)
          setSavedCountries(result)
        })
        .catch((err) =&gt; console.log('error'))
    }
    useEffect(() =&gt; {
      const result = [...savedCountries].filter((item: any) =&gt;
        item.name.toLowerCase().includes(search.toLowerCase())
      )
      setData(result)
    }, [search, savedCountries])
  
    useEffect(() =&gt; {
      fetchData()
    }, [])
  
    return [data]
  }
  
  
  </code></pre>
  <p>Header component</p>
  <pre><code>
  
  import React from 'react'
  
  import './Header.scss'
  
  export default function Header() {
    return (
      &lt;div className=&quot;header&quot;&gt;
        &lt;ul className=&quot;HeadtableRow&quot;&gt;
          &lt;li&gt;Flag&lt;/li&gt;
          &lt;li&gt;Name&lt;/li&gt;  {/* onClick must work from here */}
          &lt;li&gt;Language&lt;/li&gt;
          &lt;li&gt;Population&lt;/li&gt;
          &lt;li&gt;Region&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/div&gt;
    )
  }
  
  
  
  </code></pre>
  <p>In MainTable I'm mapping through fetched data</p>
  <pre><code>
  import React from 'react'
  
  import Header from '../Header'
  import TableRow from '../TableRow'
  
  import './mainTable.scss'
  
  export default function MainTable({ countries }: any) {
    return (
      &lt;div&gt;
        &lt;Header /&gt;
  
        &lt;table className=&quot;table&quot;&gt;
          &lt;tbody className=&quot;tableBody&quot;&gt;
            {countries &amp;&amp;
              countries.map((country?: any) =&gt; (
                &lt;TableRow
                  key={country.name}
                  flagUrl={country.flag}
                  countryName={country.name}
                  languages={country.languages}
                  population={country.population}
                  region={country.region}
                /&gt;
              ))}
          &lt;/tbody&gt;
        &lt;/table&gt;
      &lt;/div&gt;
    )
  }
  
  </code></pre>