Hello,
I’ve been trying to get websockets working, but coming up against some curious errors.
I am connecting to the Mailsac websocket server in react, using react-use-websocket
. Initially, I tested with echo.websocket.org
. Works great.
Minimum reproducible code looks like:
import useWebSocket, { ReadyState } from 'react-use-websocket';
export const WsComponent = () => {
const [socketUrl, setSocketUrl] = useState('');
const { lastJsonMessage, readyState } = useWebSocket(`wss://echo.websocket.org`, {
onOpen: () => console.log('Opened')
});
useEffect(() => {
if (lastJsonMessage !== null) {
console.log(lastJsonMessage);
}
}, [lastJsonMessage]);
const connectionStatus = {
[ReadyState.CONNECTING]: 'Connecting',
[ReadyState.OPEN]: 'Open',
[ReadyState.CLOSING]: 'Closing',
[ReadyState.CLOSED]: 'Closed',
[ReadyState.UNINSTANTIATED]: 'Uninstantiated',
}[readyState];
return <p>{connectionStatus}</p>;
}
This connects.
Then I went over to https://sock.mailsac.com/, and tested my key and email there. This web page was able to connect to Mailsac websockets.
So now it’s time to connect to Mailsac in React!
import useWebSocket, { ReadyState } from 'react-use-websocket';
const apiKey = 'k_<my_key>'; // redacted
const email = '[email protected]'; // not my email
const socketUrl = `wss://sock.mailsac.com/incoming-messages?key=${apiKey}&addresses=${email}`;
export const WsComponent = () => {
const { lastJsonMessage, readyState } = useWebSocket(socketUrl, {
onOpen: () => console.log('Opened'),
shouldReconnect: (closeEvent) => true,
reconnectAttempts: 10,
reconnectInterval: (attemptNumber) =>
Math.min(Math.pow(2, attemptNumber) * 1000, 10000),
});
const connectionStatus = {
[ReadyState.CONNECTING]: 'Connecting',
[ReadyState.OPEN]: 'Open',
[ReadyState.CLOSING]: 'Closing',
[ReadyState.CLOSED]: 'Closed',
[ReadyState.UNINSTANTIATED]: 'Uninstantiated',
}[readyState];
return <p>{connectionStatus}</p>;
}
Fails constantly with console error:
react-dom-global:react-dom:2 WebSocket connection to 'wss://sock.mailsac.com/incoming-messages?key=k_<my_key>&[email protected]' failed:
Is someone able to please reproduce this, and help sanity check me? Clearly I’m doing something wrong, but I cannot for the life of me figure out what.