UNPKG

haystack-react

Version:

Project Haystack utilities for building React applications

60 lines 2.35 kB
/* * Copyright (c) 2021, J2 Innovations. All Rights Reserved */ import { useEffect, useState } from 'react'; import { useClient } from './client'; import { useWatch } from './watch'; /** * A hook that allows using a point from an haystack server as react state. * * Important: This hooks requires a ClientContext to work. @see https://github.com/j2inn/haystack-nclient * * @example <caption>Example of usage with a numeric point.</caption> * * const point= useReadByFilter('point and temp and zone and sp').grid[0] // One-shot reading the first point that matches the filter * const [pointValue, setPointValue, updatedPoint] = useHaystackPoint<HNum>(point) // Using the point state * * @param originaryPoint point dict used to retrieve its id and initial value. * @param pollRate poll rate for the value subscription. Expressed in seconds. * @param writeOptions default options for the write callback. * @returns Returns the point value, a function to update it and the point dict. */ export function useHaystackPoint(originaryPoint, pollRate = 5, writeOptions) { const [currentValue, setCurrentValue] = useState(); const [readValue, point] = useReadHaystackPoint(originaryPoint, pollRate); const write = useWriteHaystackPoint(originaryPoint?.id, writeOptions); const writeFunc = write ? async (val, options) => { const result = await write?.(val, options); setCurrentValue(val); return result; } : undefined; useEffect(() => { setCurrentValue(readValue); }, [readValue]); return [currentValue, writeFunc, point]; } function useReadHaystackPoint(originalPoint, pollRate = 5) { const { grid: [point], isLoading, } = useWatch({ ids: originalPoint?.id, pollRate: pollRate, }); return isLoading ? [originalPoint?.curVal, originalPoint] : [point?.curVal, point]; } function useWriteHaystackPoint(id, generalOptions) { const client = useClient(); return id ? (val, options) => client.ops.pointWrite({ id: id, level: generalOptions?.level ?? 17, who: generalOptions?.who, duration: generalOptions?.duration, ...options, val: val, }) : undefined; } //# sourceMappingURL=useHaystackPoint.js.map