I am working on a notification system with push notifications for a project and can't seem to properly set up a minimal WebSocket connection just to test that everything is working, P.S (I am new to WebSockets).
For the Api I am using spring boot, here is what I have now:
useEffect(() => {
if (user) {
const sock = new SockJS('http://localhost:8080/ws');
stompClient = over(sock);
stompClient.connect({}, onError);
stompClient.subscribe('/all/public', onPublicMessageReceived);
stompClient.subscribe(`/user/${user.id}/private`, onPrivateMessageReceived);
}
}, []);
const onPublicMessageReceived = (payload: any) => {
const payloadData = JSON.parse(payload.body);
console.log(payloadData);
};
const onError = (error: any) => {
console.log(error);
};
const onPrivateMessageReceived = (payload: any) => {
const payloadData = JSON.parse(payload);
console.log(payloadData);
};
const handleSendPublicMessage = () => {
if (stompClient) {
const randomData: any = {
data: 'random',
};
stompClient.send('/app/message', {}, JSON.stringify(randomData));
}
};
And here are my imports:
import SockJS from 'sockjs-client';
import { over } from '@stomp/stompjs';
Here it gives me this error:
Module '"@stomp/stompjs"' has no exported member 'over'.ts(2305)
Then if I try to change the import declaration to this:
import { over } from 'stompjs';
It doesn't immediately show any errors and it even seems like typescript recognized it, but when the app compiles it shows this error:
Module not found: Error: Can't resolve 'stompjs' in 'C:\CODE\PROJECTS\VSCODE\kau-2023-spring-tautvydas-fe\src\components\header\Notifications'
ERROR in ./src/components/header/Notifications/NotificationsDropdown.tsx 12:0-31
Module not found: Error: Can't resolve 'stompjs' in 'C:\CODE\PROJECTS\VSCODE\kau-2023-spring-tautvydas-fe\src\components\header\Notifications'
Here are the dependencies I have installed:
- npm install u/stomp/stompjs ws
- npm install @stomp/stompjs
- npm install --save @types/stompjs
- npm i net
- npm i sockjs-client
- npm i --save-dev @types/sockjs-client
Most of the tutorials I've found use react with vanilla JS and most of the problems I am facing seem to do with typescript itself Does anyone have any ideas how to fix these issues and set up a WebSocket connection using react with typescript? I would greatly appreciate any help :)