Adam Norton
Adam Norton

Reputation: 570

Can I set.State and Sort at the same time?

In my app I fetch some data and set.State into an array. Later I map that array, but would like to sort it first. To me, the most convenient would be to sort it by name at the time of set.State. I have tried several things, none have come even close. How can I convert this to sort during or before set.State? I would prefer to do it here if I can figure it out, so that my array is alphabetical from the beginning.

componentDidMount() {
        fetch(API_URL + '/api/clients/all')
            .then(res => {
                if (!res.ok) {
                    throw new Error();
                }
                return res.json();
            })
            .then((result) => {
                this.setState({ clients: result });
                console.log(result);
            })
            .catch(error => {
                console.log(error);
            })

I've also as my second option trying to sort it by name just before mapping it, so it'll appear alphabetically on screen. This is also failing miserably, here's how far I've gotten, but it doesn't work either.

{this.state.clients.sort((a, b) => a.client.localeCompare(b.client)
  .map(client => (
       <StyledCard style={{ width: '18rem' }}>
           <Card.Img className="image-cap" variant="top" src={client.logo} />
           <Card.Body>
               <Card.Title>{client.client}</Card.Title>
               <Card.Text>
                {client.city}, {client.state}, {client.zip}
               </Card.Text>
           </Card.Body>
        </StyledCard>
    )))}

Upvotes: 1

Views: 708

Answers (1)

Drew Reese
Drew Reese

Reputation: 202751

Array::sort

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

The return value

The sorted array. Note that the array is sorted in place, and no copy is made.

This means you can do `this.setState({ clients: result.sort() });

componentDidMount() {
    fetch(API_URL + '/api/clients/all')
        .then(res => {
            if (!res.ok) {
                throw new Error();
            }
            return res.json();
        })
        .then((result) => {
            this.setState({
              clients: result.sort(
                (a, b) => a.client.localeCompare(b.client)
              )
            });
            console.log(result); // <-- will log mutated/sorted array
        })
        .catch(error => {
            console.log(error);
        });

Depending on your response array shape you may need to pass sort a callback comparator function. Something like:

For strings

this.setState({
  clients: result.sort((a, b) => a.PropertyA.localeCompare(b.PropertyA)),
})

For numbers

this.setState({
  clients: result.sort((a, b) => a.PropertyA - b.PropertyA),
})

CompareFunction Description

Upvotes: 1

Related Questions