This is the way I am doing things with function components in v6 - there may a better way though.
import React, { useState, useEffect } from 'react';
import { PanelProps } from '@grafana/data';
import { getDataSourceSrv } from '@grafana/runtime';
import { Datasource } from './types';
...
const MyPanel: React.FC<PanelProps> = props => {
const [datasource, setDatasource] = useState<Datasource>();
...
// Setting the datasource in state - will pass down to child components in props if needed
useEffect(() => {
const dataSourceSrv: any = getDataSourceSrv();
let datasource: any = null;
Object.keys(dataSourceSrv.datasources).forEach((key: string) => {
if (dataSourceSrv.datasources[key].meta.id === 'THE_DATASOURCE_ID') {
datasource = dataSourceSrv.datasources[key];
}
});
if (datasource) {
setDatasource(datasource);
}
}, []);
const handleButtonOnClick = async () => {
const response = await props.datasource.customMethod().catch((error: Error) => {
doSomethingWithError(error);
});
if (response) {
doSomethingWithResponse(response);
}
};
...
};
...