Yes Im dumb. Coming from 6 years of React dev and building my first app with Svelte. The tutorial was fun but now im trying to actually just build and I'm confused with how a store works. I can't seem to google the right question and AI has not been helpful in the slightest. I've read the docs and am clearly missing something.
I have a user store which checks firebase and returns the user. (code below) and I want to consume the user data and pass its values with an API call. However the router keeps breaking when I try to use $user or unsubscribe in the call. The only way I've gotten it to work to avoid $ and skip the unsubscribe method and I have a feeling I'm missing the whole point.
Works, but it seems like weird logic to have to subscribe just to read the value.
import { user } from "$lib/firebase";let userData;user.subscribe((_userData) => {userData = _userData;});
- Breaks the router? (wtf? only error "stop is not a function"). (I thought this was supposed to be how it worked)
import { user } from "$lib/firebase";myFunc({user: $user})
- Attempt to unsubscribe from working method (#1) and it breaks the router again ("stop is not a function")
let userData;const unsubscribe = user.subscribe((_userData) => {userData = _userData;});onDestroy(() => {unsubscribe();} );
//firebase.jsfunction userStore() {let unsubscribe;if (!auth || !globalThis.window) {console.warn("Auth is not initialized or not in browser");const { subscribe } = writable(null);return {subscribe,};}const { subscribe } = writable(auth?.currentUser ?? null, async (set) => {unsubscribe = onAuthStateChanged(auth, async (user) => {if (user) {// Grab the user document from firestoreconst userDocRef = doc(db, "users", user.uid);const userDocSnap = await getDoc(userDocRef);const userData = userDocSnap.data();set(userData);} else {set(null);}});return () => {if (unsubscribe) {unsubscribe();}};});return {subscribe,};}export const user = userStore();