useMetricField
Subscribes to the metric selected in a metric
field and returns its current value. See In-depth: Metrics.
function useMetricField(props: {field: string}): ChannelValue | null
tip
This hook re-renders the widget for every new value of the metric, even if the value didn't change. If the widget only
needs to re-render when a derived value changes, e.g. a rounded number, use
useMemoizedMetricField.
Arguments
| Property | Type | Description |
|---|---|---|
| field | string | The name of the field. |
Returns
The ChannelValue of the metric, containing the metric, its type, its unit and its
current value. Returns null while no metric is selected, until the first value arrives, and while the metric has no
value.
Errors
- Throws a
MetricDoesNotExistErrorif the selected metric doesn't exist. - Throws an
Errorif the selected metric doesn't match thetypesorvalueTypesfilters of the field.
MoBro handles both errors, see In-depth: Error Handling.
Example
src/widgets/example/Example.tsx
import React from 'react'
import {useMetricField} from '@modbros/dashboard-sdk'
import type {ChannelValue} from '@modbros/dashboard-core'
export default function Example() {
const channelValue: ChannelValue | null = useMetricField({field: 'metric'})
if (!channelValue) {
return null
}
return (
<span>
{channelValue.metric.label}: {channelValue.value.value} {channelValue.unit.abbreviation}
</span>
)
}
To format the value based on its type, use useFormattedMetricValue.