I am fetching data(a contact list: name, email, phone, etc)from API. The mapping is done and I can see the list of names displayed but now I want them in alphabetical order from a-z.
I am trying this but i get "Unhandled Rejection(typeError): a.name.localCompare is not a function).
How can I solve it?
const UserList = () => {
const [users, setUsers] = useState([])
const [selectedUser, setSelectedUser] = useState()
const [showUser, setShowUser] = useState(true)
const onHandleClick = () => setShowUser(false)
const DisplayUser =(user) => {
setSelectedUser(user);
setShowUser(true);
}
useEffect(() => {
fetch(URL)
.then(res => res.json())
.then(json => setUsers(json));
}, [])
return (
<>
<Header>
<h1>Contact list</h1>
</Header>
<Container>
<div>
{users.sort((a,b) => a.name.localCompare(b.name))
.map(user => (
<div key={user.id}>
<User onClick ={() => DisplayUser(user)}>{user.name}</User>
</div>
))}
</div>
CodePudding user response:
You have typo it's localeCompare() method, not localCompare