Skip to content

Commit e87af34

Browse files
Update dependencies and refactor authentication logic in App component
- Upgraded @powersync/react to version 1.7.0 and @powersync/web to version 1.25.1 in package.json and package-lock.json. - Updated @powersync/common dependency to version 1.36.0. - Refactored authentication logic in App component to use useEffect for fetching user ID from Supabase on component mount, simplifying the code by removing unnecessary state management for authentication status. - Adjusted SupabaseConnector to streamline the anonymous sign-in process.
1 parent d1f9c0b commit e87af34

5 files changed

Lines changed: 43 additions & 132 deletions

File tree

package-lock.json

Lines changed: 15 additions & 15 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212
},
1313
"dependencies": {
1414
"@journeyapps/wa-sqlite": "^1.2.5",
15-
"@powersync/react": "^1.5.3",
16-
"@powersync/web": "^1.23.0",
15+
"@powersync/react": "^1.7.0",
16+
"@powersync/web": "^1.25.1",
1717
"@supabase/supabase-js": "^2.50.2",
1818
"react": "^19.1.0",
1919
"react-dom": "^19.1.0",

src/App.tsx

Lines changed: 12 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import "./App.css";
22
import { useQuery, useStatus } from "@powersync/react";
33
import { COUNTER_TABLE, type CounterRecord } from "./powersync/AppSchema";
4-
import { useState } from "react";
4+
import { useEffect, useState } from "react";
55
import { powerSync } from "./powersync/System";
66
import { connector } from "./powersync/SupabaseConnector";
77

88
function App() {
99
const [userID, setUserID] = useState<string | null>(null);
10-
const [isAuthenticating, setIsAuthenticating] = useState(false);
11-
const [authError, setAuthError] = useState<string | null>(null);
10+
// const [isAuthenticating, setIsAuthenticating] = useState(false);
11+
// const [authError, setAuthError] = useState<string | null>(null);
1212
const status = useStatus();
1313

1414
// Example of a watch query using useQuery hook
@@ -17,45 +17,15 @@ function App() {
1717
`SELECT * FROM ${COUNTER_TABLE} ORDER BY created_at ASC`
1818
);
1919

20-
// Function to fetch and set the current user's ID from Supabase auth session
21-
// Handles both existing sessions and new anonymous authentication
22-
const fetchUserID = async () => {
23-
if (isAuthenticating) {
24-
console.log("Already authenticating, skipping...");
25-
return;
26-
}
27-
28-
setIsAuthenticating(true);
29-
setAuthError(null);
30-
31-
try {
32-
console.log("Fetching user ID from Supabase...");
33-
34-
// First check if we already have a session
35-
let session = connector.currentSession;
36-
37-
if (!session) {
38-
// Only sign in anonymously if we don't have a session
39-
session = await connector.signInAnonymously();
40-
}
20+
// Get the current authenticated user's ID from Supabase on component mount
21+
useEffect(() => {
22+
const getCurrentUser = async () => {
23+
const { data: { user } } = await connector.client.auth.getUser();
24+
setUserID(user?.id || null);
25+
};
4126

42-
const userId = session?.user?.id;
43-
44-
if (userId) {
45-
setUserID(userId);
46-
} else {
47-
const errorMsg = "No user ID found in session";
48-
console.error(errorMsg);
49-
setAuthError(errorMsg);
50-
}
51-
} catch (error) {
52-
const errorMsg = `Authentication failed: ${error}`;
53-
console.error(errorMsg);
54-
setAuthError(errorMsg);
55-
} finally {
56-
setIsAuthenticating(false);
57-
}
58-
};
27+
getCurrentUser();
28+
}, []);
5929

6030
// Example of executing a native SQLite query using PowerSync
6131
// This demonstrates how to directly execute SQL commands for data mutations
@@ -75,12 +45,8 @@ function App() {
7545
const createCounter = async () => {
7646
// Ensure user is authenticated before creating counter
7747
if (!userID) {
78-
if (isAuthenticating) {
79-
console.log("Authentication in progress, please wait...");
80-
return;
81-
}
8248
console.log("No user ID, attempting to authenticate...");
83-
await fetchUserID();
49+
// await fetchUserID();
8450

8551
// If still no userID after fetch, don't proceed
8652
if (!userID) {
@@ -100,12 +66,6 @@ function App() {
10066
}
10167
};
10268

103-
// Check for existing session when component mounts
104-
// This runs only once when the app first loads
105-
if (!userID && !isAuthenticating && !authError) {
106-
fetchUserID();
107-
}
108-
10969
return (
11070
<div className="app-container">
11171
{/* Top row with Status, Logo, and Helpful Links in a grid like counter-grid */}
@@ -131,8 +91,6 @@ function App() {
13191
<div><strong>lastSyncedAt:</strong> {status.lastSyncedAt?.toLocaleString() ?? "N/A"}</div>
13292

13393
<div><strong>User ID:</strong> {userID || "Not authenticated"}</div>
134-
{isAuthenticating && <div><strong>Status:</strong> Authenticating...</div>}
135-
{authError && <div style={{ color: 'red' }}><strong>Auth Error:</strong> {authError}</div>}
13694
</>
13795
)}
13896
</div>

src/powersync/SupabaseConnector.ts

Lines changed: 10 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,7 @@ export class SupabaseConnector
4242
readonly client: SupabaseClient;
4343
readonly config: SupabaseConfig;
4444

45-
ready: boolean;
4645
currentSession: Session | null;
47-
private initializationPromise: Promise<void>;
48-
private signingIn: boolean = false;
4946

5047
constructor() {
5148
super();
@@ -67,24 +64,6 @@ export class SupabaseConnector
6764
}
6865
);
6966
this.currentSession = null;
70-
this.ready = false;
71-
72-
// Restore session from localStorage
73-
this.initializationPromise = this.initializeSession();
74-
}
75-
76-
private async initializeSession(): Promise<void> {
77-
try {
78-
const { data, error } = await this.client.auth.getSession();
79-
if (error) {
80-
console.error("Failed to restore session:", error);
81-
} else if (data?.session) {
82-
console.log("Restored session:", data.session);
83-
this.updateSession(data.session);
84-
}
85-
} catch (error) {
86-
console.error("Error during session initialization:", error);
87-
}
8867
}
8968

9069
/**
@@ -108,49 +87,19 @@ export class SupabaseConnector
10887
// }
10988

11089
async signInAnonymously() {
111-
// Wait for initialization to complete first
112-
await this.initializationPromise;
113-
114-
// Check if we already have a valid session
115-
if (this.currentSession) {
116-
return this.currentSession;
117-
}
118-
119-
// Prevent concurrent sign-in attempts
120-
if (this.signingIn) {
121-
console.log("Already signing in, waiting...");
122-
// Wait for the current sign-in to complete
123-
while (this.signingIn) {
124-
await new Promise(resolve => setTimeout(resolve, 100));
125-
}
126-
return this.currentSession;
127-
}
90+
const { data: { user } } = await this.client.auth.getUser();
91+
if (user?.id) return;
12892

129-
try {
130-
this.signingIn = true;
131-
132-
// Double-check session after acquiring lock
133-
if (this.currentSession) {
134-
console.log("Session acquired while waiting");
135-
return this.currentSession;
136-
}
137-
138-
const {
139-
data: { session },
140-
error
141-
} = await this.client.auth.signInAnonymously();
142-
143-
if (error) {
144-
throw error;
145-
}
146-
147-
console.log("Signed in anonymously:", session);
148-
this.updateSession(session);
93+
const {
94+
data: { session },
95+
error
96+
} = await this.client.auth.signInAnonymously();
14997

150-
return session;
151-
} finally {
152-
this.signingIn = false;
98+
if (error) {
99+
throw error;
153100
}
101+
102+
this.updateSession(session);
154103
}
155104

156105
async logout() {

src/powersync/System.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,4 +65,8 @@ export const powerSync = new PowerSyncDatabase({
6565
* 🔧 Quick prototype → Keep default (IndexedDB)
6666
*/
6767

68+
// Sign in the user anonymously to Supabase (creates a temporary user session)
69+
await connector.signInAnonymously();
70+
71+
// Establish connection between PowerSync and the Supabase connector
6872
powerSync.connect(connector);

0 commit comments

Comments
 (0)