Skip to content

Commit

Permalink
fix: reconnect race condition (#3643)
Browse files Browse the repository at this point in the history
* fix: reconnect race condition

* Create quick-hairs-nail.md

---------

Co-authored-by: jxom <jakemoxey@gmail.com>
  • Loading branch information
TateB and jxom authored Mar 17, 2024
1 parent 6d13bec commit e46bcd4
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 9 deletions.
6 changes: 6 additions & 0 deletions .changeset/quick-hairs-nail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@wagmi/core": patch
"wagmi": patch
---

Fixed race condition arising from `reconnect`.
8 changes: 8 additions & 0 deletions packages/core/src/actions/reconnect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,11 @@ test("behavior: doesn't reconnect if already reconnecting", async () => {
).resolves.toStrictEqual([])
config.setState((x) => ({ ...x, status: previousStatus }))
})

test("behaviour: doesn't overwrite connected status", async () => {
config.setState((x) => ({ ...x, status: 'connected' }))
await expect(
reconnect(config, { connectors: [connector] }),
).resolves.toStrictEqual([])
expect(config.state.status).toEqual('connected')
})
24 changes: 15 additions & 9 deletions packages/core/src/actions/reconnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,15 +106,21 @@ export async function reconnect(
connected = true
}

// If connecting didn't succeed, set to disconnected
if (!connected)
config.setState((x) => ({
...x,
connections: new Map(),
current: undefined,
status: 'disconnected',
}))
else config.setState((x) => ({ ...x, status: 'connected' }))
// Prevent overwriting connected status from race condition
if (
config.state.status === 'reconnecting' ||
config.state.status === 'connecting'
) {
// If connecting didn't succeed, set to disconnected
if (!connected)
config.setState((x) => ({
...x,
connections: new Map(),
current: undefined,
status: 'disconnected',
}))
else config.setState((x) => ({ ...x, status: 'connected' }))
}

isReconnecting = false
return connections
Expand Down

0 comments on commit e46bcd4

Please sign in to comment.