SignalR connect setup in react- using useEffects

Viewed 214

I'm using "@microsoft/signalr": "^6.0.5", and trying to set up a connection.

It is able to connect with the backend, but I am not sure if my setup looks OK for when the connection fails.

Specifically, I am wondering if the last useEffect is correctly written (the placement of the onClose clause)

useEffect(() => {
    const newConnection = new HubConnectionBuilder()
      .withUrl(
        "https://localhost:3000/workorderHub",
        { accessTokenFactory: () => token, withCredentials: false }
      )
      .configureLogging(LogLevel.Information)
      .withAutomaticReconnect()
      .build();

    setConnection(newConnection);
  }, []);

  useEffect(() => {
    async function start() {
      if (connection) {
        try {
          connection
            .start()
            .then(() => {
              connection.invoke("SubscribeToProject", projectId); // calling hub method from the client
            })
            .catch((err) => {
              console.error(err.toString());
            });

          connection.on(
            "OperationUpdated",
            (projectId, operationId, operation) => {
              // function called from the backend Hub
              actions.updateSyncedOperation({ operationId, operation });
            }
          );
        } catch (err) {
          console.log({ err });
          setTimeout(start, 5000);
        }
      } else {
        connection.onclose(async () => {
          await start();
        });
      }
    }
    start();
  }, [connection]);
0 Answers
Related