Reputation: 247
I am sorting a table and when I click, the order goes to ascending but not descending. I have a boolean value that should toggle true or false but it keeps logging out the initial value. Can someone help me understand why the if statement isn't working? Also when I sort how do I return to the original array?
let sortDirection = false;
const sortTable = (key) => {
sortDirection = !sortDirection
const clonedOptions = [...listOfOptions];
clonedOptions.sort((a, b) => {
return sortDirection ? a[key] - b[key] : b[key] - a[key];
})
setListOfOptions(clonedOptions);
}
<div className="outputs" >
<table>
<thead>
<tr>
<th></th>
<th onClick={() => sortTable('clock')}>Date </th>
<th onClick={() => sortTable('name')}>Stock Name</th>
<th onClick={() => sortTable('price')}>Price Of Option</th>
<th onClick={() => sortTable('amountOfOptions')}>Number Of Options</th>
<th onClick={() => sortTable('totalAmountSpent')}>Total Amount Spent</th>
<th onClick={() => sortTable('optionPriceSoldAt')}>Option Sold At</th>
<th onClick={() => sortTable('amountOfOptionsSold')}>Amount Of Options Sold</th>
<th onClick={() => sortTable('totalProfit')}>Proft</th>
</tr>
</thead>
{listOfOptions.map((option) => {
return (
<tbody key={uuidv1()}>
<tr>
<td title="delete" onClick={() => deleteOption(option.id)}><span className="delete">x</span></td>
<td>{option.clock}</td>
<td>{option.name.toUpperCase()}</td>
<td>${option.price}</td>
<td>{option.amountOfOptions}</td>
<td>${option.totalAmountSpent.toFixed(2)}</td>
<td>${option.optionPriceSoldAt}</td>
<td>{option.amountOfOptionsSold}</td>
<td style={{ color: option.totalProfit >= 0 ? 'green' : 'red' }}>${option.totalProfit.toFixed(2)}</td>
</tr>
</tbody>
)
})}
</table>
</div>
</div>
Upvotes: 0
Views: 1690
Reputation: 370689
You need to put the boolean into state, otherwise, on each render, it'll start out as false
:
const [sortDirection, setSortDirection] = useState(false);
const sortTable = (key) => {
setSortDirection(!sortDirection);
const clonedOptions = [...listOfOptions];
clonedOptions.sort((a, b) => {
return sortDirection ? b[key] - a[key] : a[key] - b[key];
})
setListOfOptions(clonedOptions);
}
Upvotes: 2