react-stomp-hooks useStompClient hook set to undefined on page refresh

2.3k Views Asked by At

I am using the react-stomp-hooks package to establish a websocket stomp connection with my backend. I have a function component which renders a certain page where I define const stompClient = useStompClient() and on component mount I have a useEffect() which is supposed to publish via stomp directly after the first render. Now the issue is that my defined stompClient is undefined when I refresh the page, however on rendering the page for the first time (via routing from another page), everything works smoothly. The exact TypeError is Cannot read property 'publish' of undefined. What am I not seeing here? See my code:

const SomePage = () => {
  ...
  const stompClient = useStompClient();


  useEffect(() => {
    stompClient.publish({
      destination: `/app/some_destination`,
      body: 'some-string'
    });

    ...
  }, [])
...
}

EDIT1:

I figured that the stompClient is set to undefined since the connection to the backend has to be set up again on page refresh and the useEffect is being called before this setup has taken place. So I need a way to trigger the stompClient.publish() only after connection establishment but I dont know how to achieve this. My top most <App/> component is wrapping everything in a <StompSessionProvider/> (see linked package doc) but how can I listen to an established connection of this StompSessionProvider?

class App extends Component {
  render() {
    return (
      <div>
        <StompSessionProvider
            brokerURL={`${getWebsocketDomain()}/websocket`}
            debug={STOMP => console.log({STOMP})}
            onConnect={() => console.log({STOMP_CONNECT: 'TCP connection successfully established'})}
        >
          <AppRouter />
        </StompSessionProvider>
      </div>
    );
  }
}
1

There are 1 best solutions below

0
On

Perhaps like this:

const SomePage = () => {
  ...
  const stompClient = useStompClient();


  useEffect(() => {
    if(stompClient.connected) {
       stompClient.publish({
         destination: `/app/some_destination`,
         body: 'some-string'
       });
    }

    ...
  }, [stompClient.connected])
...
}