Skip to content

Commit

Permalink
🐛 Use Ref for Callback function to always use latest function, withou…
Browse files Browse the repository at this point in the history
…t reconnecting on every update
  • Loading branch information
SvenKirschbaum committed Jan 24, 2021
1 parent 0d12f1f commit e94ce15
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/hooks/useSubscription.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useContext, useEffect } from 'react'
import { useContext, useEffect, useRef } from 'react'
import StompContext from '../context/StompContext'

/**
Expand All @@ -9,16 +9,25 @@ import StompContext from '../context/StompContext'
*/
function useSubscription(destinations, onMessage, headers = {}) {
const stompContext = useContext(StompContext)
const callbackRef = useRef()
const _destinations = Array.isArray(destinations)
? destinations
: [destinations]

callbackRef.current = onMessage

useEffect(() => {
const cleanUpFunctions = []

_destinations.forEach((_destination) =>
cleanUpFunctions.push(
stompContext.subscribe(_destination, onMessage, headers)
stompContext.subscribe(
_destination,
(message) => {
callbackRef.current(message)
},
headers
)
)
)

Expand Down

0 comments on commit e94ce15

Please sign in to comment.