useNextId.ts 757 B

12345678910111213141516171819
  1. import { useMemo } from 'react';
  2. import { BucketAggregation } from '../components/QueryEditor/BucketAggregationsEditor/aggregations';
  3. import { useQuery } from '../components/QueryEditor/ElasticsearchQueryContext';
  4. import { MetricAggregation } from '../components/QueryEditor/MetricAggregationsEditor/aggregations';
  5. const toId = <T extends { id: unknown }>(e: T): T['id'] => e.id;
  6. const toInt = (idString: string) => parseInt(idString, 10);
  7. export const useNextId = (): MetricAggregation['id'] | BucketAggregation['id'] => {
  8. const { metrics, bucketAggs } = useQuery();
  9. return useMemo(
  10. () =>
  11. (Math.max(...[...(metrics?.map(toId) || ['0']), ...(bucketAggs?.map(toId) || ['0'])].map(toInt)) + 1).toString(),
  12. [metrics, bucketAggs]
  13. );
  14. };