McBood
McBood

Reputation: 7

Why doesn't react re-render the page on button click?

function App() {
    const [users,setUsers] = useState([])

    useAsyncEffect(async () => {
        const res = await fetch('https://jsonplaceholder.typicode.com/users')
        const data = await res.json()
        setUsers(data)
    }, [])
    
    console.log(users)

    function sortCity () {
        users.sort((x,y) => {
            if(x.address.city < y.address.city) {return -1}
            if(x.address.city > y.address.city) {return 1}
            return 0
        })
        
        console.log(users)
    }

    function sortCompany () {
        users.sort((x,y) => {
            if(x.company.name < y.company.name) {return -1}
            if(x.company.name > y.company.name) {return 1}
        return 0
    })

    console.log(users)
}

<SortButton button={sortCity} text="по городу" />
<SortButton button={sortCompany} text="по компании"/>

Console logs are displayed, but it doesn't re-render.

Upvotes: 0

Views: 356

Answers (1)

Georgy
Georgy

Reputation: 1939

.sort array method mutates the state and you should avoid this. You cannot mutate anything in React, because it is not able to re-render. You should set the new state directly.

In your case you should create a new array, sort it, and set into your state:

function sortCompany () {
 const sortedUsers = [...users]

 sortedUsers.sort((x,y) => {
   if(x.company.name < y.company.name) {return -1}
   if(x.company.name > y.company.name) {return 1}
   return 0
 })

 setUsers(sortedUsers);
}

Upvotes: 3

Related Questions