How to load API data into vue 3 grid

I am working on an application where I need to load data on component load. Where I am binding ag-grid-vue. I am facing an issue my Api response is late and grid gives an show below.

caught (in promise) TypeError: rowData.map is not a function

Here is my code on component load

<script>
  import { AgGridVue } from "ag-grid-vue3";
  import Repository from "../serviceFactory/serviceFactory";
  const jokeRepository = Repository.get("JokeRepo");
  
  export default{
    name: "App",
    components: {
      AgGridVue,
    },
    data() {
       var jokeList = jokeRepository.getRecordList().then(res => {return res});
       debugger
      return {
        columnDefs: [
          { headerName: "Joke", field: "joke",sortable: true}
        ],
        rowData: jokeList,
        overlayNoRowsTemplate: "No Record Found!"
      };
   }
  }
  </script>

Here jokeList is return a PromiseState pending.

>Solution :

You are setting jokeList (and consecutively rowData) to a promise, not a list:

var jokeList = jokeRepository.getRecordList()

Instead, initialize rowData as an empty array:

data() {
  return {
    ...
    rowData: [],
  };
}

and then load the data in a lifecycle hook like created, and update rowData from there:

created(){
  jokeRepository.getRecordList().then(res => this.rowData = res)
}

Leave a Reply