Tarasovych
Tarasovych

Reputation: 2398

Return and set reversed value

I'm making sorting logic fo a table.

What I have now:

What I want to do: reverse sort param after successful data fetch via axios.
I mean if it was sortParams.id = 'id', it might be changed to sortParams.id = '-id'.
I made a method which can handle this:

reverseSortParam(param) {
    if (param.charAt(0) === '-') {
        return param.replace('-', '')
    }
    return '-' + param
}

How can I use reverseSortParam() inside sort()? I mean, sort() accepts only string value, and I need to pass the source of the string value to reverseSortParam() somehow.


UPD: Some shitcode which might work, but there is no place for it in my project:

<th @click="sort(sortParams.created_at, 'created_at')">Date</th>`

sort(param, paramName) {
    let that = this
    axios.get(process.env.API_BASE_URL + process.env.API_BASE_VERSION + 'data?sort=' + param + '&page=' + that.tableData.current_page)
        .then(function (response) {
            that.tableData = response.data
            that.sortParams[paramName] = that.reverseSortParam(param)
        })
}

JSFiddle

Upvotes: 1

Views: 301

Answers (1)

Sumurai8
Sumurai8

Reputation: 20737

I think you are over-engineering this. You are keeping a table of potential future sort parameters, but not the current state. You also want to change this table based on a value. On top of that you can currently only sort on a single attribute, but keep the (previous) state of sorting, causing effectively random behaviour for the user that is using it.

Consider changing the following:

data () {
  return {
    // Maps local names to api names
    sortMap: {
      created_at: 'created_at',
      time: 'datetime',
      id: 'id'
    },

    // The default sort
    sortParam: 'created_at'
  },

  methods: {
    async sort (localName) {
      // Figure out if we need to inverse the current sort
      const currentSort = this.sortParam.replace('-', '');

      // Set the current sort
      if (currentSort === this.sortMap[localName]) {
        this.sortParam = `-${this.sortParam}`.replace('--', '');
      } else {
        this.sortParam = this.sortMap[localName];
      }

      this.getData()
    },

    async getData () {
      // You probably want to factor out the api calls to their own file anyway
      this.tableData = await axios.get(..).data
    }
  }
}

Now instead of having your logic scattered around the place, you simply call sort('created_at') from your template. The method makes sure we use the correct sorting parameter and getData() in this case uses this sorting parameter

Upvotes: 1

Related Questions