Search code examples
javascriptreactjsasynchronoussignalr

React SignalR HubConnection doesn't send data to server


I'm trying to do an application that connects to a SignalR hub and sends information when buttons are clicked but for some reason it's not sending anything.

const bannerId = 1;

const App = () => {

useEffect(() => {
    let newConnection = new HubConnectionBuilder()
      .withUrl('https://localhost:7116/bannerHub')
      .withAutomaticReconnect()
      .build();
    setConnection(newConnection);
  }, []);

  useEffect(() => {
    if (connection) {
      connection.start()
        .then(result => {
          console.log('Connected!');

        })
        .catch(e => console.log('Connection failed: ', e));
    }
  }, [connection]);
  
  const disableBanner = async (evt) => {
    await connection.send('DisableBanner', bannerId);
  }

  const enableBanner = async (evt) => {
    await connection.send('EnableBanner', bannerId);
  }

return(
<>
<button onClick={async () => { await disableBanner(); }} className='btn btn-primary'>Disable banner</button>
          <button onClick={async () => { await enableBanner(); }} className='btn btn-primary'>Enable banner</button>
</>
);
}

The package that I'm using is @microsoft/signalr and the connection object it's a HubConnection.

Does anyone knows what am I doing wrong?

Thank you and I hope this helps to others with the same problem!


Solution

  • I've solve it.

    My problem was on the server side. SignalR methods where waiting for a string bannerId and I was sending them an int (or Number in JS). I thought that data binding was going to fix this but for some reason that doesn't works here.

    The two possible solutions are:

    1. Change the SignalR methods to receive int bannerId instead of string bannerId
    2. Change react component to send a bannerId: string instead of bannerId: number.

    That was all. Thank you all for the comments.