Use range in datasource resource

For a datasource plugin I’m building I want to provide the user with a dropdown menu which displays the options based on the selected timerange. I’ve currently implemented a resource handler that takes a POST with the time range as the request body which works well enough. The trouble I’m running into is that the range thats included in the QueryEditor props doesn’t seem to update when the range is changed.

In the example below the range is only updated when the editor is loaded in, but not when it is changed later. Is there any way to get the updated range from this stage?

export function QueryEditor(props: EditorProps) {
  const { datasource, query, onChange, onRunQuery, range } = props;

  const { loading, value: projects = [], error } = useProjects(datasource, range);
  const onChangeProject = (selectable: SelectableValue<string>) => {
    const project = selectable?.value;
    if (project) {
      onChange({ ...query, project });
      onRunQuery();
    }
  };

  return (
    <InlineFieldRow>
      <InlineField label="Project">
        <Select
          options={projects}
          onChange={onChangeProject}
          isLoading={loading}
          value={toSelectableValue(query.project)}
          error={error}
        />
      </InlineField>
    </InlineFieldRow>
  );
}

type AsyncReturnType = {
  loading: boolean;
  value?: Array<SelectableValue<string>>;
  error?: Error | undefined;
};

function useProjects(datasource: DataSource, range?: TimeRange): AsyncReturnType {
  return useAsync(async () => {
    console.log('retrieving projects', range?.to.toString(), range?.from.toString());
    const projects = await datasource.getAvailableProjects(range);

    return projects.map((project) => ({
      label: project,
      value: project,
    }));
  }, [range]);
}

function toSelectableValue(value: string | undefined): SelectableValue<string> | undefined {
  if (!value) {
    return;
  }
  return {
    label: value,
    value: value,
  };
}

Hi @ysmilda I can confirm the QueryEditor props are updated with the new range when a new range is selected. Here’s a recording of a freshly bootstraped data source plugin which only modification is in the QueryEditor component to print the time range as:

  console.log('range from', props.data?.timeRange.from.format('YYYY-MM-DD HH:mm:ss'));
  console.log('range to', props.data?.timeRange.to.format('YYYY-MM-DD HH:mm:ss'));

I also did the test with:

 console.log('range from', props.range.from.format('YYYY-MM-DD HH:mm:ss'));
  console.log('range to', props.range.to.format('YYYY-MM-DD HH:mm:ss'));

which produced the same expected results.

Peek 2024-08-15 16-13

it is more likely something in your custom hooks is caching the old values and that’s why they are not updating when the user changes the time range.