I'm new to react and I want to create a list which can be sorted with price(salary). My api response is suppose -
[
{
"id":1,
"name": "Person 1",
"salary": 300
},
{
"id":2,
"name": "Person 2",
"salary": 100
},
{
"id":3,
"name": "Person 3",
"salary": 200
}
]
I'm trying to use hooks useState and useEffect to get my data and populate the UI
const salary = () => {
const [salaryState, setsalaryState] = useState([]);
const [load, setLoad] = useState(false);
const [geterror, setError] = useState('');
useEffect(() => {
axios.get('https://apiCall')
.then(response => {
setsalaryState(response.data);
setLoad(true);
})
.catch(error => {
setError(error.message);
console.log('error', geterror);
})
},[]);
const handleSalrySort = () => {
var sortAsc = salaryState.sort((a,b) => {
return parseFloat(a.salary) - parseFloat(b.salary)
});
setsalaryState(sortAsc);
console.log('sortAsc', sortAsc);
}
if(load){
return (
<div className="container-fluid pt-3">
<div onClick={handleSalrySort}>Salary - Low to High</div>
{
salaryState.map((sal,index) => {
return(
<div>
Person : {sal.name}
Salary: {sal.salary}
</div>
)
})
}
</div>
)
}else{
return(
<div></div>
)
}
}
Ater the handleSalrySort function I'm able to update the state salaryState but it's not reflecting on the UI. Can you please help me with that?