Accessing Datasource from Panel

Hello,
I am trying to make a new react panel plugin which allows me to upload a config file and save it to the database. I have done something similar on grafana 6 where I if I extend MetricsPanelCtrl I can just call

(in the onClick handler)
this.datasource.custommethod().then(
handle results.
)

However, in Grafana 7 the panel is a function component. So there is no this state. My question is how do I get the datasource in the new framework and ensure it is a type that can call my custom methods?

thanks,
Dennis

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);
    }
  };

  ...

};

...

Thanks Jeremy, worked like a charm

1 Like