Johnny
Johnny

Reputation: 1

Automatically sort an API list by name in Vue js

Hello I am new in the field of Vue,js and am stuck on a certain problem. I have an API list with different data points that I am trying to sort by first_name and Load onto the page:

<template>
  <div> 

    
    <div class="content-card">
      <h1 class="title">List of users</h1>



      <div v-for="peopleData in peopleDataList.data"  :key ="peopleData.id" class="people-data">
        <div @load="sort('first_name')" v-bind:class="[sortBy === 'first_name' ? sortDirection : '']">
  
        
          <div class="user-icon">
            <img :src="peopleData.avatar" alt="Connection lost please reload">
          </div>

          
          <div class="user-info">
            <div class="user-full_name"> 
              {{peopleData.first_name}}
              {{peopleData.last_name}}
            </div>

            <div class="user-email">
              <!-- {{peopleData.email}} -->
            </div>
          </div>
          
          
          <!-- make a mdel to display as menu with the data  -->

        </div>
      </div>
    </div>

  </div>
</template>

<script>



export default {
  name: "List",


  data() {
    return {
      peopleDataList: [],
      sortBy: 'name',
      sortDirection: 'asc',
    };
  }, 


// automatically call the data 
  created() {
    this.getpeopleData();
  },


  methods: {
    getpeopleData() {
      fetch("https://reqres.in/api/users?page=2")
        .then(response => response.json())
        .then(data => (this.peopleDataList = data));
    },



    sort: function(s){
      if(s === this.sortBy) {
        this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
       }
        this.sortBy = s;
    }
  },

  watch: {
            sortedProducts: function(){
                return this.products.sort((p1,p2) => {
                    let modifier = 1;
                    if(this.sortDirection === 'desc') modifier = -1;
                    if(p1[this.sortBy] < p2[this.sortBy]) return -1 * modifier; if(p1[this.sortBy] > p2[this.sortBy]) return 1 * modifier;
                    return 0;
                });
            }
        },



};
</script>

I've seen multiple guides using @click to solve this problem but I wanted to have it automatically sort when its loaded. I am still new to Vue.js so please go easy on me.

Upvotes: 0

Views: 665

Answers (1)

Tim
Tim

Reputation: 1229

You don't need <div @load ... I recommend sorting the users in your getPeopleData() method, similar to this:

<template>
  <div class="initial-data-sort">
    <table class="table table-bordered">
      <thead>
        <tr>
          <th>ID</th>
          <th>NAME</th>
          <th>EMAIL</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.id">
          <td>{{ user.id }}</td>
          <td>{{ user.name }}</td>
          <td>{{ user.email }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
  import axios from 'axios'

  export default {
    data() {
      return {
        users: [],
        usersSorted: []
      }
    },
    methods: {
      getUsers() {
        axios.get('https://jsonplaceholder.typicode.com/users')
          .then(response => {
            this.users = response.data;
            // Sort users
            this.users.sort(this.compareNames);
          })
          .catch(error => console.log(error));
      },
      compareNames(a, b) {
        const nameA = a.name.toLowerCase();
        const nameB = b.name.toLowerCase();

        let comparison = 0;
        if (nameA > nameB) {
          comparison = 1;
        } else if (nameA < nameB) {
          comparison = -1;
        }
        return comparison;
      }
    },
    created() {
      this.getUsers();
    }
  }
</script>

I sometimes keep a sorted version of the data array, hence the inclusion of 'usersSorted', but possibly not necessary in your case.

Upvotes: 1

Related Questions