Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug in CollectionStore - (No Loading State) #96

Open
anasmohammed361 opened this issue Jun 12, 2023 · 0 comments
Open

Bug in CollectionStore - (No Loading State) #96

anasmohammed361 opened this issue Jun 12, 2023 · 0 comments

Comments

@anasmohammed361
Copy link

anasmohammed361 commented Jun 12, 2023

The loading slot is triggered when the $store == undefined , But as the writable store is of type T[] , it defaults to [] even when we explicitly pass undefined, so the loading state never gets triggered to over come this we can add type to writable to make it accept undefined value as its initial state, Here is the updated code

export function collectionStore<T>(
  firestore: Firestore,
  ref: string | Query | CollectionReference,
  startWith: T[]|undefined = undefined
) {
  let unsubscribe: () => void;

  // Fallback for SSR
  if (!firestore || !globalThis.window) {
    console.warn('Firestore is not initialized or not in browser');
    const { subscribe } = writable(startWith);
    return {
      subscribe,
      ref: null,
    }
  }

  const colRef = typeof ref === 'string' ? collection(firestore, ref) : ref;

  const { subscribe } = writable<T[] | undefined>(startWith, (set) => {
    unsubscribe = onSnapshot(colRef, (snapshot) => {
      const data = snapshot.docs.map((s) => {
        return { id: s.id, ref: s.ref, ...s.data() } as T;
      });
      set(data);
    });
    return () => unsubscribe();
  });

  return {
    subscribe,
    ref: colRef,
  };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant