Просмотр исходного кода

[frontend] Extend the useHuePubSub hook to allow callbacks

Johan Åhlén 2 лет назад
Родитель
Сommit
f944a878b7

+ 19 - 0
desktop/core/src/desktop/js/reactComponents/useHuePubSub.test.tsx

@@ -51,4 +51,23 @@ describe('useHuePubSub', () => {
 
     expect(result.current).toEqual('some info');
   });
+
+  test('triggers a callback with the info when a message is published', () => {
+    let callbackCalled = false;
+    renderHook(() =>
+      useHuePubSub<string>({
+        topic: 'my.test.topic',
+        callback: a => {
+          expect(a).toEqual('some info');
+          callbackCalled = true;
+        }
+      })
+    );
+
+    act(() => {
+      publishCallback('some info');
+    });
+
+    expect(callbackCalled).toBeTruthy();
+  });
 });

+ 27 - 4
desktop/core/src/desktop/js/reactComponents/useHuePubSub.ts

@@ -1,3 +1,19 @@
+// Licensed to Cloudera, Inc. under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  Cloudera, Inc. licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
 import { useState, useEffect } from 'react';
 import huePubSub from '../utils/huePubSub';
 
@@ -6,19 +22,26 @@ import huePubSub from '../utils/huePubSub';
 // Use with caution and preferrably only at the top level component in your component tree since
 // we don't want to have states stored all over the app.
 
-export function useHuePubSub<Type>({
+export function useHuePubSub<T>({
   topic,
+  callback,
   app
 }: {
   topic: string;
+  callback?: (info?: T) => void;
   app?: string;
-}): Type | undefined {
-  const [huePubSubState, setHuePubSubState] = useState({ info: undefined });
+}): T | undefined {
+  const [huePubSubState, setHuePubSubState] = useState<{ info: T | undefined }>({
+    info: undefined
+  });
 
   useEffect(() => {
-    const pubSub = huePubSub.subscribe(
+    const pubSub = huePubSub.subscribe<T>(
       topic,
       info => {
+        if (callback) {
+          callback(info);
+        }
         // Always create a new state so that the react component is rerendered even
         // if the info is the same as previous info. This is to stay aligned with the idea
         // of having a component being notified for EVERY message for the topics it subscribes to.