Skip to content

Bug in CollectionStore - (No Loading State) #96

Open
@anasmohammed361

Description

@anasmohammed361

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,
  };
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions