How to change a dashboard variable value from a plugin?

This definitely took some serious time/research to resolve here is how I resolved it:

  1. my dashboard variable is named ‘location_id’
  2. the variable is used in a query “select location_name from location where locationid=$location_id”
  3. when a user clicks on a popup I needed to update the variable so I could refresh the data for other visual components.
import { DataSourceApi } from '@grafana/data';
import { getDataSourceSrv } from '@grafana/runtime';

    handleOnPopup =  (e:any, locationId:number ) => {
        let dataSource:DataSourceApi = getDataSourceSrv() as unknown as DataSourceApi;    
        let variable = _.find(dataSource.templateSrv.variables, {'name':'location_id'});
        this.locationSelectedId = locationId;
        variable.query = locationId.toString(); //make string even if its a number

        variable.variableSrv.updateOptions(variable).then(() => {
            variable.variableSrv.variableUpdated(variable, true);
        });
    }

render(){
//check the data state and get your updated data          
if(data.state == "Done" && data.series[2] && data.series[2].length > 0 && data.series[2]["fields"][0]["values"].buffer[0] == this.locationSelectedId){
            
                this.locationDevices = data.series[2];

            }
}

Other Context: Custom Grafana React Plugin
Grafana Version: 6.4.4
NPM packages:
-"@grafana/runtime": “^6.6.0”
-"@grafana/data": “^6.5.1”

4 Likes