I have an array of objects, which should be sorted by the user's defined property (in dropdown). Here is the code:
import React, {useState, useEffect} from 'react';
const repos = [
{
name: 'repo1',
forks_count: 5,
stargazers_count: 3,
updated_at: 12
},
{
name: 'repo2',
forks_count: 7,
stargazers_count: 2,
updated_at: 17
},
{
name: 'repo3',
forks_count: 8,
stargazers_count: 11,
updated_at: 5
}
];
function App() {
const[data, setData] = useState([]);
const[sortType, setSortType] = useState('stars');
useEffect(() => {
const sortRepos = (type) => {
const types = {
stars: 'stargazers_count',
forks: 'forks_count',
upd: 'updated_at'
};
const sortProperty = types[type];
const sorted = repos.sort((a,b) => b[sortProperty] - a[sortProperty]);
setData(sorted);
};
sortRepos(sortType);
}, [sortType]);
return (
<div className="App">
<select onChange={(e) => setSortType(e.target.value)}>
<option value='stars'>Stars</option>
<option value='forks'>Forks</option>
<option value='upd'>Updated</option>
</select>
<div >
{data.map(repo => (
<div key={repo.name}>
<div>Name {repo.name}</div>
<div>Forks {repo.forks_count}</div>
<div>Stars {repo.stargazers_count}</div>
<div>Update {repo.updated_at}</div>
</div>
))}
</div>
</div>
);
}
But the problem is that sorted data re-renders one step behind after changing the value in the dropdown.
What am I doing wrong? My guess is that the problem is in comparing objects, as I've tested to set primitive value in data variable and everything works fine. But not with an object.