Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closing websocket connections within a react context #254

Open
kasvith opened this issue Nov 23, 2024 · 0 comments
Open

Closing websocket connections within a react context #254

kasvith opened this issue Nov 23, 2024 · 0 comments

Comments

@kasvith
Copy link

kasvith commented Nov 23, 2024

Hi, im trying to use this library with a React context, according to the description unless the component unmounts the library not closing the connections

in my case the connections being kept open, or new ones being created when context value changes. there is no way for close unwanted socket connections

export const ConversationProvider = ({
  conversationId,
  children,
}: ConversationProviderProps) => {
  const [selectedConversationId, setSelectedConversationId] = useState(
    conversationId || ""
  );

  const wsUrl = useMemo(() => {
    if (!selectedConversationId) return null;
    return `wss://example.com/conversation/${selectedConversationId}`;
  }, [selectedConversationId]);

  const handleWsMessage = useCallback((e: MessageEvent) => {
    console.log("Message received:", e.data);
    // Handle WebSocket messages here
  }, []);

  useWebSocket(
    wsUrl,
    {
      onMessage: handleWsMessage,
      retryOnError: true,
    },
    !!selectedConversationId // Determines whether the WebSocket should connect
  );

  const contextValue = useMemo(
    () => ({
      selectedConversationId,
      setSelectedConversationId,
    }),
    [selectedConversationId]
  );

  return (
    <ConversationContext.Provider value={contextValue}>
      {children}
    </ConversationContext.Provider>
  );
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant