Search code examples
reactjsaxioskendo-datasourcekendo-react-ui

Kendo DataSource reading from Async/await method which uses Axios to fetch data


Using React with TypeScript

Please could somebody provide an example of how I might be able to use a Kendo DataSource to read from a method which internally uses Axios to prod an external API for JSON data..? I must have flown through 20 different versions of this code trying different approaches, nothing seems to fit...

All I'm trying to do currently is supply a Kendo ComboBox with an array of {id: number, name: string}

Very basic stuff at the moment, but I do have to use a similar approach to this later on with a Kendo Grid which handles server side sorting and pagination so I'd like to get this working now then that should be somewhat easier later on...

The reason I want to use Axios is because I've written an api.ts file that appends appropriate headers on the gets and posts etc and also handles the errors nicely (i.e. when the auth is declined etc...)

A basic example of what I'm trying, which isn't working is this: -

public dataSource: any;

constructor(props: {}) {
super(props);

this.dataSource = new kendo.data.DataSource({
  type: "odata",
  transport: {
    read: function() {
      return [{ id: 1, name: "Blah" }, { id: 2, name: "Thing" }];
    }.bind(this)
  },
  schema: {
    model: {
      fields: {
        id: { type: "number" },
        name: { type: "string" }
      }
    }
  }
});
}

<ComboBox
   name="test"
   dataSource={this.dataSource}
   placeholder={this.placeholder}
   dataValueField="id"
   dataTextField="name"
/>

Anybody got any thoughts on this please? :)


Solution

  • Easy fix in the end...

    this.dataSource = new kendo.data.DataSource({
      transport: {
        read: function(options: any) {
          options.success([{ id: 1, name: "Blah" }, { id: 2, name: "Thing" }]);
        }.bind(this)
      },
      schema: {
        model: {
          fields: {
            id: { type: "number" },
            name: { type: "string" }
          }
        }
      }
    });
    

    2 things were wrong..

    Removed the type: "odata", and Added the usage of options in

    All working fine now with the async await function also, just passing the data into the options.success in the .then on the promise. Job done :-)