# JavaScript connection

Websocket connection using JS

```javascript
import React, { useEffect, useState } from 'react';

const WebSocketComponent = () => {
    const [ws, setWs] = useState(null);
    const API_KEY = 'YOUR_API_KEY'; // Replace with your actual API key

    useEffect(() => {
        // Create WebSocket connection.
        const webSocket = new WebSocket('wss://news.treeofalpha.com/ws');

        // Connection opened
        webSocket.onopen = (event) => {
            console.log('Connection opened');
            webSocket.send(`login ${API_KEY}`);
        };

        // Listen for messages
        webSocket.onmessage = (event) => {
            console.log('Message from server ', event.data);
        };

        // Listen for possible errors
        webSocket.onerror = (error) => {
            console.error('WebSocket error: ', error);
        };

        // Listen for the close event
        webSocket.onclose = (event) => {
            console.log('WebSocket is closed now.');
        };

        // Assign the WebSocket object to state
        setWs(webSocket);

        // Perform cleanup
        return () => {
            webSocket.close();
        };
    }, []); // The empty array causes this effect to only run on mount

    return (
        <div>
            <h1>WebSocket Example</h1>
            {/* You can add more UI elements here that interact with WebSocket */}
        </div>
    );
};

export default WebSocketComponent;

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.treeofalpha.com/websockets/javascript-connection.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
