vuematerial/vue-material

Table only renders API data correctly in local dev, not in production build

gutorsantos opened this issue · 0 comments

Hello,

I'm using a table(MD-TABLE) to render a list of data in my application, I'm on the final stage of the project thus I started a few days ago the deployment tests in a production environment allocated in Cpanel.

The issue that I'm facing is when I run the application on my local computer (development environment) the table works perfectly and shows the data as expected, however when I deploy the same code on Cpanel the data does not show up and I get a empty state. I can the data from my api call on the Network tab( chrome browser).

Expected result (dev)
image

Actual result (prod)
image

Code of the component

<template>
  <div id="generical-table">
    <md-table style="table" v-model="searched" md-sort="empreendimento" md-sort-order="asc" md-card md-fixed-header @md-selected="onSelect">
      
      <md-table-toolbar v-if="selected != null" >
        <div class="md-toolbar-section-start">{{ `1 ${title.toLowerCase().slice(0, -1)} selectionado`}}</div>

        <div class="md-toolbar-section-end">
          <md-button class="md-icon-button" @click="openNewTab()">
            <md-icon>edit</md-icon>
          </md-button>
        </div>
      </md-table-toolbar>

      <md-table-toolbar>
        <div class="md-toolbar-section-start paginator" v-if="type !== 'no-page'">
          <md-button class="md-icon-button page-button" @click="paginationRequest(paginatorData.first_page_url)" :disabled="paginatorData.current_page == 1"><md-icon>first_page</md-icon></md-button>
          <md-button class="md-icon-button page-button" @click="paginationRequest(paginatorData.prev_page_url)" :disabled="!paginatorData.prev_page_url"><md-icon>chevron_left</md-icon></md-button>
          <span v-for="(item, i) in arrayPages" :key="i">
            <md-button @click="paginationRequest(`${paginatorData.path}?page=${item[0]}`)" class="md-icon-button page-button" :class="{'number-selected': item[0] == paginatorData.current_page}">{{item[0]}}</md-button>
            <md-button @click="paginationRequest(`${paginatorData.path}?page=${item[1]}`)" class="md-icon-button page-button" :class="{'number-selected': item[1] == paginatorData.current_page}">{{item[1]}}</md-button>
            <md-button @click="paginationRequest(`${paginatorData.path}?page=${item[2]}`)" class="md-icon-button page-button" :class="{'number-selected': item[2] == paginatorData.current_page}">{{item[2]}}</md-button>
          </span>
          <md-button class="md-icon-button page-button" @click="paginationRequest(paginatorData.next_page_url)" :disabled="!paginatorData.next_page_url"><md-icon>chevron_right</md-icon></md-button>
          <md-button class="md-icon-button page-button" @click="paginationRequest(paginatorData.last_page_url)" :disabled="paginatorData.last_page == paginatorData.current_page"><md-icon>last_page</md-icon></md-button>
          <span class="md-caption page-info">{{paginatorData.from}} – {{paginatorData.to}} de {{paginatorData.total}}</span>
        </div>
        <md-field md-clearable class="md-toolbar-section-end">
          <md-input placeholder="Pesquisar por... (nesta página)" v-model="search" @input="searchOnTable" />
          <md-tooltip md-direction="bottom">{{`${headers.map(o => beautifyHeaders(o)).join(', ')}`}}</md-tooltip>
        </md-field>
        <div class="md-toolbar-section-start center">
        </div>
      </md-table-toolbar>

      <md-table-empty-state
        md-label="Sem registro"
        :md-description="`Nenhum${title === 'Empresas' ? 'a' : ''} ${title.toLowerCase().slice(0, -1)} encontrado ${search ?  ' para ' + search : ''}. Tente uma nova busca ou crie um novo registro`">
        <md-button class="md-primary md-raised" @click="redirect()">Novo</md-button>
      </md-table-empty-state>

      <md-table-row slot="md-table-row" slot-scope="{ item }" md-selectable="single" md-auto-select>
        <md-table-cell style="text-align: left;" v-for="head in headers" :key="`h-${head}`" :md-label="beautifyHeaders(head)" :md-sort-by="head">
          {{ head === 'item_id' ? findItem(item[head]) : (head === 'empresa_id' ? findCompany(item[head]) : item[head]) }}
        </md-table-cell>
      </md-table-row>
    </md-table>
  </div>
</template>

<script>

import axios from 'axios'
  const toLower = text => {
    return text.toString().toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, "")
  }
  export default {
    name: 'TableSearch',
    props: {
      formList: Object,
      headers: Array,
      type: String,
      title: String
    },
    data() {
      return {
        arrayPages: [],
        search: null,
        searched: [],
        selected: null,
        list: [],
        paginatorData: {
          current_page: null,
          first_page_url: null,
          from: null,
          last_page: null,
          last_page_url: null,
          next_page_url: null,
          path: null,
          per_page: null,
          prev_page_url: null,
          to: null,
          total: null,
          selectPerPage: null,
        },
        count: 0,
      }
    },
    methods: {
      redirect() {
        this.$router.push('/dashboard/novo')
      },
      /*  Search Filter
          If there is any term, the filter it will be done
          Search for all results searching by the header keys,
          each key will return an array of objects, if it's not empty
          it's concatenated into an array
      */
      searchTeste(items, term) {
        if(term) {
          let array = new Array()
          for (let i in this.headers) {
            let x = items.filter(item => toLower(item[this.headers[i]]).includes(toLower(term)))
            if(x.length > 0)
              array.push(...x)
          }
          // Remove duplicate objects in array
          const uniqueSet = new Set(array.map(e => JSON.stringify(e)));
          const uniqueArray = Array.from(uniqueSet).map(e => JSON.parse(e));
          return uniqueArray
        }
        // If there's no term it will return the initial list with no filter
        return items
      
      },
      // Trigged every time typed in input fiel
      searchOnTable () {
        this.searched = this.searchTeste(this.list, this.search)
      },
      onSelect (items) {
        this.selected = items
        
      },
      // Function to request new data when paginated
      async paginationRequest(url) {
        url = url.replace('http://127.0.0.1:8000/api', '')
        await axios.get(url).then(response => {
          this.list = response.data.data
          this.searched = response.data.data
          this.getAllPagedData(response.data)
        })
        this.numbersPagination()
      },
      numbersPagination() {
        let currentPage = this.paginatorData.current_page, // input
        range       = 3,  // amount of links displayed 
        totalPages  = this.paginatorData.last_page, // determined by amount of items, hardcoded for readability 
        start       = 1;  // default

        let paging = [];      // output variable

        // Don't use negative values, force start at 1
        if (currentPage < (range / 2) + 1 ) {
          start = 1;

        // Don't go beyond the last page 
        } else if (currentPage >= (totalPages - (range / 2) )) {
          start = Math.floor(totalPages - range + 1);

        } else {
          start = (currentPage - Math.floor(range / 2));
        }

        for (let i = start; i <= ((start + range) - 1); i++) {
          paging.push(i.toString());
        }
        this.arrayPages = [paging];
      },
      // Get the pagination data
      getPaginationData(response) {
        
          this.paginatorData.current_page = response.current_page
          this.paginatorData.first_page_url = response.first_page_url
          this.paginatorData.from = response.from
          this.paginatorData.last_page = response.last_page
          this.paginatorData.last_page_url = response.last_page_url
          this.paginatorData.next_page_url = response.next_page_url
          this.paginatorData.path = response.path
          this.paginatorData.per_page = response.per_page
          this.paginatorData.prev_page_url = response.prev_page_url
          this.paginatorData.to = response.to
          this.paginatorData.total = response.total
          this.selectPerPage = this.paginatorData.per_page
      },
      // Get the data of paginated informations
      getAllPagedData(response) {
        // Get paginator data
        this.getPaginationData(response)
        this.numbersPagination()
      },
      // Logic to ordinate numbers in paginator
      showPaginateNumber(num) {
        return (this.paginatorData.current_page%(this.paginatorData.current_page+num))+(num-this.paginatorData.current_page)+(this.paginatorData.current_page >= 4 ? (this.paginatorData.current_page-1) : 0)
      },
      /*  Children to parent event
          Return to the parent saying to 
          open a new tab
      */
      openNewTab() {
        this.$emit('getSelected', this.selected)
      },
      beautifyHeaders(value) {
        return this.beautify(value)
      },
      disableCondition(ativo) {
        if(!this.headers.includes('headers')) {
          return false
        }else {
          return !ativo 
        }
      },
      findItem(id) {
        return this.FIND_ITEM(id)
      },
      findCompany(id) {
        return this.companyList[this.companyList.findIndex(x => x.id === id)].razao
      }

    },
    created () {
    },
    async mounted() {
      await this.GET_EMPRESA().then(response => (this.companyList = response.data))
      this.list = this.formList.data
      this.searched = this.formList.data
      this.getAllPagedData(this.formList)
    },
  }
</script>

<style lang="scss" scoped>
    @import './Table.scss';
</style>