Skip to content

Commit

Permalink
✨ Expose client only if it is connected
Browse files Browse the repository at this point in the history
  • Loading branch information
SvenKirschbaum committed Apr 28, 2022
1 parent f719c0a commit 5e9b2f7
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 6 deletions.
16 changes: 11 additions & 5 deletions example/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,15 +72,21 @@ export function SendingMessages() {

//Get Instance of StompClient
//This is the StompCLient from @stomp/stompjs
//Note: This will be undefined if the client is currently not connected
const stompClient = useStompClient();
useSubscription("/user/queue/echoreply", (message) => setLastMessage(message.body));

const sendMessage = () => {
//Send Message
stompClient.publish({
destination: "/app/echo",
body: "Echo " + input
});
if(stompClient) {
//Send Message
stompClient.publish({
destination: "/app/echo",
body: "Echo " + input
});
}
else {
//Handle error
}
};

return (
Expand Down
9 changes: 8 additions & 1 deletion src/components/StompSessionProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,14 @@ function StompSessionProvider(props: StompSessionProviderProps) {
value.headers
);
});

setClient(_client);
};

_client.onWebSocketClose = function (event) {
if (stompOptions.onWebSocketClose) stompOptions.onWebSocketClose(event);

setClient(undefined);
};

if (!stompOptions.onStompError) {
Expand All @@ -64,7 +72,6 @@ function StompSessionProvider(props: StompSessionProviderProps) {
}

_client.activate();
setClient(_client);

return () => {
_client.deactivate();
Expand Down
1 change: 1 addition & 0 deletions src/hooks/useStompClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { StompSessionProviderContext } from '../interfaces/StompSessionProviderC

/**
* Returns the Stomp Client from @stomp/stompjs
* This will be undefined if the client is currently not connected
*/
function useStompClient() {
const context = useContext<StompSessionProviderContext | undefined>(
Expand Down

0 comments on commit 5e9b2f7

Please sign in to comment.