Search code examples
reactjskuzzle

How to re-render a component when a non state object is updated


I have an object which value updates and i would like to know if there is a way to re-render the component when my object value is updated. I can't create a state object because the state won't be updated whenever the object is. Using a ref is not a good idea(i think) since it does not cause a re-render when updated.

The said object is an instance of https://docs.kuzzle.io/sdk/js/7/core-classes/observer/introduction/


Solution

  • The observer class doesn't seem to play well with your use case since it's just sugar syntax to manage the updates with mutable objects. The documentation already has a section for React, and I suggest following that approach instead and using the SDK directly to retrieve the document by observing it.

    You can implement this hook-observer pattern

    import React, { useCallback, useEffect, useState } from "react";
    import kuzzle from "./services/kuzzle";
    
    const YourComponent = () => {
      const [doc, setDoc] = useState({});
      const initialize = useCallback(async () => {
        await kuzzle.connect();
        await kuzzle.realtime.subscribe(
          "index",
          "collection",
          { ids: ["document-id"] },
          (notification) => {
            if (notification.type !== "document" && notification.event !== "write")
              return;
            // getDocFromNotification will have logic to retrieve the doc from response
            setDoc(getDocFromNotification(notification));
          }
        );
      }, []);
    
      useEffect(() => {
        initialize();
        return () => {
          // clean up
          if (kuzzle.connected) kuzzle.disconnect();
        };
      }, []);
    
      return <div>{JSON.stringify(doc)}</div>;
    };