Skip to content

Fix double API calls on first wallet connect — race condition in useConnectedIdentity #632

@realproject7

Description

@realproject7

Problem

On first wallet connect, useConnectedIdentity fires two parallel requests that both hit external APIs:

  1. Line 31: register-by-wallet (fire-and-forget) — SteemHunt → Neynar → saves to DB
  2. Line 40: getFarcasterProfile(address) — checks DB (empty) → falls through to SteemHunt → Neynar

Result: double SteemHunt + Neynar API calls on every first connect. The profile fetch doesn't wait for register to populate the DB.

On subsequent page loads this isn't an issue — DB is already populated.

Fix

Await the register call before fetching the profile, so the DB is populated first:

useEffect(() => {
  if (!address) return;
  let cancelled = false;

  async function init() {
    // Step 1: Register (populates DB with SteemHunt/Neynar data)
    if (registeredRef.current !== address) {
      registeredRef.current = address;
      try {
        await fetch("/api/user/register-by-wallet", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ walletAddress: address }),
        });
      } catch {
        // Non-fatal
      }
    }

    // Step 2: Now fetch profile (DB is populated, no external API needed)
    if (!cancelled) {
      const p = await getFarcasterProfile(address);
      if (!cancelled) setResult({ profile: p, resolvedFor: address });
    }
  }

  init();
  return () => { cancelled = true; };
}, [address]);

This ensures:

  • First connect: register → DB populated → profile reads from DB (1 API call total, not 2)
  • Subsequent loads: register returns cached (5-min cooldown) → profile reads from DB (0 API calls)

Files to modify

  • src/hooks/useConnectedIdentity.ts — await register before fetching profile

Branch

task/632-fix-connect-race

Acceptance criteria

  • First wallet connect only makes 1 round of SteemHunt/Neynar calls (not 2)
  • Profile still resolves correctly on first connect
  • Subsequent page loads read from DB (no external API calls)
  • No visible delay increase for the user (register is fast)
  • Build passes

Self-Verification (T3)

  • Run npm run dev, open Network tab, connect wallet for the first time (clear localStorage/cookies first)
  • Count requests to fc.hunt.town (SteemHunt) — should be exactly 1 batch, not 2
  • Count requests to api.neynar.com — should be 0 or 1 (fallback only), not doubled
  • Verify Farcaster profile still displays correctly in nav after connect
  • Disconnect and reconnect — verify profile loads from DB (no external API calls)
  • Run npm run build — no errors

Metadata

Metadata

Assignees

No one assigned

    Labels

    agent/T3Assigned to T3 builder agent

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions