Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Translation return key and not value after refreshing page #152

Closed
nwood-personal opened this issue Dec 12, 2023 · 4 comments
Closed

Translation return key and not value after refreshing page #152

nwood-personal opened this issue Dec 12, 2023 · 4 comments

Comments

@nwood-personal
Copy link

Hello,

My translation are displaying the key instead the value for some reason....
When i navigate from an other page to this page everything look fine but when im reloading the page everything come back in key and not value.....

Component vue:
data(){ return{ header:'', colDefs: [ { field: "id", editable: false, checkboxSelection: true}, { field: "resp_id", headerName: trans("entry.responsible"), editable: false }, { field: "company_name", headerName: 'Company name', filter: true}, { field: "visit_subject",headerName: 'visit subject', filter: true}, { field: "contact",headerName: 'Contact interne', filter: true }, { field: "entry_date", headerName: 'Entry Date'}, { field: "exit_date", headerName: 'Exit date'}, ], } },

the trans function in the coldefs array return the key and not the value bute everything is fine on other pages

@xiCO2k
Copy link
Owner

xiCO2k commented Dec 12, 2023

Thanks for the report @nwood-personal. can you provide more context to figure the problem?

@nwood-personal
Copy link
Author

nwood-personal commented Dec 13, 2023

I have an onboarding app for our guest in our company with laravel 10 and vue 3.
I have the package ag-grid installed for my table display and it take an array coldefs to define the header and header name.
I want the header to be also translated so i added the trans() function to traduce them. But when im visiting the page the translation are good but when im reloading the page everything go back to key.

My table vue component:

<template>
  <div class="w-10/12 mx-auto pt-10">
      <button class="px-3 py-2 my-2 border border-black rounded-lg mr-2 bg-red-500 text-white disabled:opacity-40" disabled id="btnDelete" v-on:click="onBtDelete">{{ $t("delete") }}</button>
      <button class="px-3 py-2 my-2 border border-black rounded-lg bg-blue-600 text-white disabled:opacity-40" disabled id="btnView" v-on:click="onBtView">{{ $t("view") }}</button>
      <ag-grid-vue
      class="h-[60vh] ag-theme-quartz"
      :rowData="rowData"
      :columnDefs="this.colDefs"
      :editType="editType"
      @grid-ready="onGridReady"
      @row-selected="onRowSelected"
      @rowEditingStopped="rowEditingStopped"
      :defaultColDef="defaultColDef"
      :rowSelection="'single'"
      ></ag-grid-vue>
  </div>
</template>

<script>
import { ref } from 'vue';
import "ag-grid-community/styles/ag-grid.css"; // Core CSS
import "ag-grid-community/styles/ag-theme-quartz.css"; // Theme
import { AgGridVue } from "ag-grid-vue3"; // Vue Grid Logic
import { useRouter } from 'vue-router'
import { trans } from 'laravel-vue-i18n'

window.timeOperation = function timeOperation(name, operation) {
  aggCallCount = 0;
compareCallCount = 0;
filterCallCount = 0;
var start = new Date().getTime();
operation();
var end = new Date().getTime();
console.log(
  name +
    ' finished in ' +
    (end - start) +
    'ms, aggCallCount = ' +
    aggCallCount +
    ', compareCallCount = ' +
    compareCallCount +
    ', filterCallCount = ' +
    filterCallCount
);
};
var aggCallCount = 0;

var compareCallCount = 0;

var filterCallCount = 0;
export default {
data(){
  return{
    header:'',
    colDefs: [
          { field: "id", editable: false, checkboxSelection: true},
          { field: "resp_id", headerName: trans("entry.responsible"), editable: false },
          { field: "company_name", headerName: 'Company name', filter: true},
          { field: "visit_subject",headerName: 'visit subject', filter: true},
          { field: "contact",headerName: 'Contact interne', filter: true },
          { field: "entry_date", headerName: 'Entry Date'},
          { field: "exit_date", headerName: 'Exit date'},
      ],
  }
},
components: {
  AgGridVue, // Add AG Grid Vue3 component
},
methods: {
  rowEditingStopped(event) {
    var data = event.data;
    delete data['resp_id'];
    axios.patch(`api/groupes/${data.id}`,data).then((res) => {
      console.log(res);
    })
  }
},
setup() {
  const router = useRouter();
  const rowData = ref([]);
  // Row Data: The data to be displayed.
  axios.get(`api/groupes`).then((res) => {
      rowData.value = res.data.data;
  })

  const gridApi = ref();

  const onGridReady = (params) => {
    gridApi.value = params.api;
  };
  
  const onBtDelete =() =>{
    // get the first child of the
      var selectedRow = gridApi.value.getSelectedRows();

      if (!selectedRow || selectedRow.length === 0) {
          console.log('No rows selected!');
          return;
      }

      selectedRow.forEach(element => {
        axios.delete(`api/groupes/${element.id}`).then(() => {
          timeOperation('Delete', () => {
            gridApi.value.applyTransaction({ remove: selectedRow });
          });
        }).catch((error) => {
          console.log(error.response.data);
        });
      });
  };

  const onBtView =()=>{
    var selectedRow = gridApi.value.getSelectedRows();
    if (selectedRow.length === 1) {
      var id = selectedRow[0].id;
      router.push({
          name: 'details',
          query: {
              group_id: id
          }
      })
    }else{
      console.log('too much row selected');
    }
  };

  const onRowSelected = () => {
    var selectedRow = gridApi.value.getSelectedRows();
    if (!selectedRow || selectedRow.length === 0) {
        document.getElementById('btnDelete').disabled = true;
        document.getElementById('btnView').disabled = true;
    }else{
      document.getElementById('btnDelete').disabled = false;
        document.getElementById('btnView').disabled = false;
    }
  };
// Column Definitions: Defines & controls grid columns.
  return {
      rowData,
      defaultColDef: {
          editable: true,
      },
      gridApi,
      editType: 'fullRow',
      onGridReady,
      onBtDelete,
      onRowSelected,
      onBtView,
  };
},
};
</script>

my app.js :

import './bootstrap';
import '../css/app.css';
import { createApp } from 'vue';
import App from './layouts/App.vue';
import router from './router.js';
import axios from 'axios'
import { i18nVue } from 'laravel-vue-i18n'; 

const apiClient = axios.create({
    baseURL: '/api',
    withCredentials: true,
});

export default {
    getUser() {
        return apiClient.get('/user');
    },
};


const app = createApp(App)
app.config.globalProperties.$axios = axios;
app.use(i18nVue, { 
    resolve: async lang => {
        const langs = import.meta.glob('../../lang/*.json');
        return await langs[`../../lang/${lang}.json`]();
    }
})
app.use(router)
app.mount('#app')

and the welcome blade:

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Montremo - Welcome</title>
    </head>
    <body class="backdrop-blur">

    <div class="absolute top-2 left-5 flex space-x-3 text-primary-memo bg-gray-500 bg-opacity-50">
        <a class="opacity-100" href="{{ url('locale/en') }}" ><i class="fa fa-language"></i> EN</a>
        <a class="opacity-100" href="{{ url('locale/fr') }}" ><i class="fa fa-language"></i> FR</a>
    </div>
    @if (Auth::check())
    <script>
        window.Laravel = {!!json_encode([
            'isLoggedin' => true,
            'user' => Auth::user()
        ])!!}
    </script>
    @else
        <script>
            window.Laravel = {!!json_encode([
                'isLoggedin' => false
            ])!!}
        </script>
    @endif
        @vite('resources/js/app.js')
        <div id="app"></div>
    </body>
</html>

@Keanu97
Copy link

Keanu97 commented Jan 2, 2024

I have the same issue, it works for me when hot reload is happening with vite but when I refresh the page, the data get's lost. Only the key will show. Any update for this issue? @xiCO2k

@xiCO2k
Copy link
Owner

xiCO2k commented Jan 3, 2024

Hey, sorry for the delay, there are some options to solve your issue:

  1. Change the import plugin to non lazy load, like this:
app.use(i18nVue, { 
    resolve: async lang => {
        const langs = import.meta.glob('../../lang/*.json', { eager: true });
        return langs[`../../lang/${lang}.json`].default;
    }
})
  1. Make use of the wTrans instead of trans:

The trans method is not reactive so it only loads once and since some times the page loads before the translation file is loaded it can return the key.

  1. Create a watch to check if the translation is loaded with isLoaded() method.

After that you can use the trans method will get the translation for your key.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants