robtaussig / react-use-websocket

React Hook for WebSocket communication
MIT License
1.63k stars 135 forks source link

lastMessage undefined if not named 'lastMessage' #149

Closed SaremS closed 2 years ago

SaremS commented 2 years ago

Hi,

is this intended:

const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl);

is working fine, but

const { sendMessage2, lastMessage2, readyState2 } = useWebSocket(socketUrl);

results in lastMessage2===undefined

Thanks!

koralarts commented 2 years ago

This is expected. useWebSocket returns an object -- see doc. You are destructuring that object whenever you write const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl);. This means the names within the {} are keys that exist in the returned object. You can rename those in your destructure by { sendMessage: sendMessage2 }.

More Info:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring

robtaussig commented 2 years ago

Thanks @koralarts