Reputation: 101
I am using React Hooks. I am trying to sort the data that I fetch from an API and update the state with the newly sorted data.
const [runs, setRuns] = useState({
runs: [],
});
const [altConcentrationRuns, setAltConcentrationRuns ] = useState({
altConcentrationRuns : []
})
async function handleRuns() {
getRuns().then((result) => {
setRuns(result.rows);
setFilteredRuns(result.rows);
//function to sort data according to column header/property
const sortRowsByProperty = (property, direction) => {
return result.rows.sort(function(a,b) {
var A = Object.keys(a)[0];
var B = Object.keys(b)[0];
if(direction == "ascending") {
return (a[A][property] - b[B][property]);
} else if(direction == "descending") {
return b[B][property] - a[A][property];
}
});
}
setAltConcentrationRuns(sortRowsByProperty('altConcentration', 'ascending'));
//not updating, only showing runs
setIsLoading(false);
});
}
useEffect(() => {
setIsLoading(true);
handleRuns();
}, []);
console.log('runs', altConcentrationRuns);
When I console log my output, I don't get the sorted data, only the original data (result.rows). What am I doing wrong?
Thanks!
Upvotes: 1
Views: 70
Reputation: 10349
The problem is your sorting function. In JS to sort items, it's common practice to return -1
when a < b
, 0
when a == b
and 1
when a > b
. You can often omit the ==
condition and just return -1
or 1
if (direction === "ascending") {
return a[A][property] < b[B][property] ? -1 : 1
} else if (direction === "descending") {
return a[A][property] < b[B][property] ? 1 : -1
}
This can be optimized further, but keeping it similar to your code for understandability.
Upvotes: 1
Reputation: 628
I see one problem in your code. you are initializing your state in the wrong way.
const [runs, setRuns] = useState([]);
const [altConcentrationRuns, setAltConcentrationRuns ] = useState([])
This is how your state should be initialized. docs for useState
Upvotes: 1