lukeed / sockette

The cutest little WebSocket wrapper! 🧦
MIT License
2.45k stars 81 forks source link

Still in CONNECTING state #47

Open iDVB opened 5 years ago

iDVB commented 5 years ago

First time I've used sockets in a while...

I'm building a simple react voting example that allows a room of people to click as many times and as fast as they want on one of 6 choices and that will cast their vote.

This definitely seems like an issue with how fast everything can process each vote.

However, I'm not sure where to start?

This is the bulk of the code:

  const onVote = vote => {
    console.log({ vote, ws });
    ws.json({
      action: 'sendMessage',
      data: JSON.stringify(vote)
    });
  };

  const onMessageReceied = ({ data }) => {
    console.log({ data });
    const voteData = JSON.parse(data);
    console.log({ onMessageReceied: voteData });
    setBallotsList({ ...ballotsList, ...voteData });
  };

  useEffect(() => {
    console.log({ ballotsList });
    ws = new Sockette(config.site.api, {
      timeout: 5e3,
      maxAttempts: 1,
      onopen: e => console.log('connected:', e),
      onmessage: e => onMessageReceied(e),
      onreconnect: e => console.log('Reconnecting...', e),
      onmaximum: e => console.log('Stop Attempting!', e),
      onclose: e => console.log('Closed!', e),
      onerror: e => console.log('Error:', e)
    });
    return function cleanup() {
      ws && ws.close();
      ws = null;
    };
  }, [ballotsList]);
hakimio commented 5 years ago

You just have to wait for connection to be established before you can start sending messages.