Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/full-humans-create.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/devtools-utils': patch
---

fix issue with client connectivity by not calling the connect method multiple times
34 changes: 24 additions & 10 deletions packages/event-bus-client/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,12 @@ export class EventClient<
#connectEveryMs: number
#retryCount = 0
#maxRetries = 5
#connecting = false

#onConnected = () => {
this.debugLog('Connected to event bus')
this.#connected = true
this.#connecting = false
this.debugLog('Emitting queued events', this.#queuedEvents)
this.#queuedEvents.forEach((event) => this.emitEventToBus(event))
this.#queuedEvents = []
Expand All @@ -41,30 +44,39 @@ export class EventClient<
this.#onConnected,
)
}
#connectFunction = () => {
this.#eventTarget().addEventListener(
'tanstack-connect-success',
this.#onConnected,
)
// fired off right away and then at intervals
#retryConnection = () => {
if (this.#retryCount < this.#maxRetries) {
this.#retryCount++
this.dispatchCustomEvent('tanstack-connect', {})

return
}

this.#eventTarget().removeEventListener(
'tanstack-connect',
this.#connectFunction,
this.#retryConnection,
)

this.debugLog('Max retries reached, giving up on connection')
this.stopConnectLoop()
}

// This is run to register connection handlers on first emit attempt
#connectFunction = () => {
if (this.#connecting) return
this.#connecting = true
this.#eventTarget().addEventListener(
'tanstack-connect-success',
this.#onConnected,
)
this.#retryConnection()
}

constructor({
pluginId,
debug = false,
enabled = true,
reconnectEveryMs = 1000,
reconnectEveryMs = 300,
}: {
pluginId: TPluginId
debug?: boolean
Expand All @@ -83,16 +95,18 @@ export class EventClient<
}

private startConnectLoop() {
// if connected, trying to connect, or the internalId is already set, do nothing
if (this.#connectIntervalId !== null || this.#connected) return
this.debugLog(`Starting connect loop (every ${this.#connectEveryMs}ms)`)

this.#connectIntervalId = setInterval(
this.#connectFunction,
this.#retryConnection,
this.#connectEveryMs,
) as unknown as number
}

private stopConnectLoop() {
this.#connecting = false
if (this.#connectIntervalId === null) {
return
}
Expand Down Expand Up @@ -203,7 +217,7 @@ export class EventClient<
pluginId: this.#pluginId,
})
// start connection to event bus
if (typeof CustomEvent !== 'undefined') {
if (typeof CustomEvent !== 'undefined' && !this.#connecting) {
this.#connectFunction()
this.startConnectLoop()
}
Expand Down
Loading
Loading