H.Husain
H.Husain

Reputation: 463

Cannot read property 'sort' of undefined in reactjs

I am getting following error TypeError: Cannot read property 'sort' of undefined when I am fetching the data from API and I want to sort and display the data, my sort function works with local static data but not with endpoint.

Below is the function for sorting

dynamicSort(property) {
        var sortOrder = 1;
        if(property[0] === "-") {
            sortOrder = -1;
            property = property.substr(1);
        }
        return function (a,b) {
            if(sortOrder == -1){
                return b[property].localeCompare(a[property]);
            }else{
                return a[property].localeCompare(b[property]);
            }        
        }
    }

Below is my render method

render() {
let data = this.props.brands.all_brands
data.sort(this.dynamicSort("name"));
console.log(data);
}

Below is my JSON Format

{
"all_items": [
{"name": "Banana"},
{"name": "Cat"},
{"name": "Apple"}
]
}

Upvotes: 0

Views: 10876

Answers (2)

Andrei Voicu
Andrei Voicu

Reputation: 750

Remote data is asynchronous, meaning it takes time to get it, so you need to treat the case in which you haven't got it yet:

all_brands is undefined, until the remote data is fetched:

render() {
    let data = this.props.brands.all_brands

    if (data) {
        data.sort(this.dynamicSort("name"));
        console.log(data);
    } else {
        return 'loading...'    
    }
}

Upvotes: 1

messerbill
messerbill

Reputation: 5629

JS tries to call the sort() method on a variable which is undefined at this time. I guess that your props are not passed at this time. If you are sure that you pass them to the component any time, you can simply add an if check:

render() {
  let data = this.props.brands.all_brands
  if (data) data.sort(this.dynamicSort("name"));
  console.log(data);
  // return your template
}

Upvotes: 2

Related Questions