I'm creating a table by pulling the information from the API. There is a button next to the head of each table. Let's say I click the button next to the name, it should sort by name. If I click it again, it should change the name order. OrderBy takes a string like "Id", "Name" in the API URL and sorts accordingly. Ascending reverses the order when it is true or false. So I created two states. When I click the buttons it doesn't work the first time, I have to click twice. I'm not sure, but it probably has something to do with my calling getProductList right after changing the state. How can I solve this?
Initial states must be true and "Id":
const [ascending, setAscending] = useState(true);
const [orderBy, setOrderBy] = useState("Id");
handleSort function:
const handleSort = (e) => {
setOrderBy(e.target.name);
setAscending(!ascending);
getProductList();
};
API URL:
`api/common/products/getProductsAll?page=1&pageSize=30&orderBy=${orderBy}&ascending=${ascending}&Code=&Name=`
Table:
return (
<div className={styles.container}>
<button onClick={() => console.log(orderBy,ascending)}>xxx</button>
<Table striped bordered hover variant="dark">
<thead>
<tr>
<th>
<span>Ürün Kodu</span>
<button name="Id" onClick={(e) => handleSort(e)}>
o
</button>
</th>
<th>
<span>Ürün Adı</span>
<button name="Name" onClick={(e) => handleSort(e)}>
o
</button>
</th>
<th>
<span>Fiyat</span>
<button name="Price" onClick={(e) => handleSort(e)}>
o
</button>
</th>
<th>
<span>Para Birimi</span>
<button name="CurrencyId" onClick={(e) => handleSort(e)}>
o
</button>
</th>
<th>
<span>Birim Seti</span>
<button name="Unit" onClick={(e) => handleSort(e)}>
o
</button>
</th>
<th>
<span>İşlemler</span>
<button>o</button>
</th>
</tr>
</thead>
<tbody>
{list?.map((v) => {
return (
<tr key={v.Id}>
<th>{v.Code}</th>
<th>{v.Name}</th>
<th>{v.Price}</th>
<th>Adet</th>
<th>TL</th>
<th>-</th>
</tr>
);
})}
</tbody>
</Table>
</div>
);
};