msmith1114
msmith1114

Reputation: 3231

React: Array sort not reading state value?

So im working on a pretty basic CRUD app to strengthen my react skills. Right now it's a table of sensors with a state that looks like this:

this.state = {
      sensors: [
        {
          id: "1",
          name: "Temp001DEV",
          device: "Temp",
          temp: "56.4",
          humidity: "33.1",
          active: true
        },
        {
          id: "2",
          name: "Humidity002DEV",
          device: "Humidity",
          temp: "",
          humidity: "45.6",
          active: true
        }
      ],
      filterName: "",
      sortBy: "name"
    };
  }

(Few demo sensors tossed in there for some fake data).

I also have a sorting function (It's a WIP, my javascript is rusty). That looks like so:

 filterSort = () => {
    //Check for filter, then sort
    if (this.state.filterName !== "") {
      const filteredSensors = this.state.sensors.filter(sensor =>
        sensor.name.toLowerCase().includes(this.state.filterName.toLowerCase())
      );
      console.log(filteredSensors);
      return filteredSensors.sort(function(a, b) {
        if(a.name < b.name) {
          return -1;
        }
        if(a.name > b.name) {
          return 1;
        }
        else {
          return 0;
        }
      });
    } 
    //If no filter exists, just sort
    else {
      return this.state.sensors.sort(function(a, b) {
        if(a.name < b.name) {
          return -1;
        }
        if(a.name > b.name) {
          return 1;
        }
        else {
          return 0;
        }
      });;
    }
  };

The table is created by mapping through the returned "Filtered/Sorted" array and the table is created that way (Which works). I also have dropdowns and a text input that update the sortBy and filterName state (Which also works).

Where im running into issues is where i actually call sort on the filteredSensors. Right now I have a.name < b.name etc... (Which does work). But I want it to actually sort based on the state value sortBy (Which can be either name, active, or device based on a dropdown I have). However when I try to do something like const sortVal = this.state.sortBy and then swap out .name for .sortVal it doesn't work.

It will just say that the sortVal is never used. Any ideas on how to swap out the sorting based off a state value?

Thanks!

Upvotes: 0

Views: 41

Answers (1)

JoelAK
JoelAK

Reputation: 370

You're trying to use a variable called "sortVal" on the elements on the sort function by using dot notation. If you instead use a[sortVal] and b[sortVal] it will work as it will instead use the variable that sortVal evaluates to (such as humidity) as intented.

Upvotes: 2

Related Questions