After fetching data from a random profile API, I am trying to implement a feature where I can sort my profile cards by either age or last name with just a click of a button.
Although I managed to get a sorted array displayed in the console log using the handle function, the UI did not reflect these changes. I seem to be missing something in my code and would greatly appreciate any help or guidance.
function App() {
const baseURL = `https://randomuser.me/api`;
const [profiles, setProfiles] = useState([]);
const [singleProfile, setSingleProfile] = useState([]);
const showProfiles = useCallback(() => {
axios.get(baseURL).then((response) => {
setProfiles(response.data.results);
});
}, [baseURL]);
const showProfile = useCallback(() => {
axios.get(baseURL).then((response) => {
setSingleProfile(response.data.results);
});
}, [baseURL])
useEffect(() => {
showProfiles();
showProfile();
}, [showProfiles, showProfile]);
const deleteProfile = (profileId) => {
setProfiles(prevState => prevState.filter(profile => profile.id.value !== profileId))
}
const addProfile = () => {
showProfile();
setProfiles(prevState => [...prevState, ...singleProfile]);
}
const handleSortByAge = () => {
const profilesSortedByAge = profiles.sort((a, b) => {
if (a.dob.age > b.dob.age) {
return 1;
} else {
return -1;
}
})
console.log('click and profiles', profiles);
return setProfiles(profilesSortedByAge);
}
const handleSortByLastName = () => {
const profilesSortedByLastName = profiles.sort((a, b) => {
if (a.name.last > b.name.last) {
return 1;
} else {
return -1;
}
})
setProfiles(profilesSortedByLastName);
}
if (!profiles) return null;
return (
<div className="App">
<ProfilesPage
profiles={profiles}
showProfiles={showProfiles}
deleteProfile={deleteProfile}
addProfile={addProfile}
setProfiles={setProfiles}
handleSortByAge={handleSortByAge}
handleSortByLastName={handleSortByLastName}
/>
</div>
);
}
export default App;