Skip to content

infinity loading #11

@himself65

Description

@himself65

https://discord.com/channels/740090768164651008/752920140483526677/1239597351866208313

  const idAtom = atom<string | null>(null);

  const resolveInitialMessages = async (id: string | null) => {
    if (!id) {
      return [];
    }

    return typeof initialMessages === 'function'
      ? await initialMessages(id)
      : initialMessages;
  };

  const primitiveMessagesAtom = atom<Message[] | Promise<Message[]> | null>(
    typeof initialMessages === 'function' ? null : initialMessages
  );

  const initialMessagesAtom = atomWithSuspenseQuery((get) => ({
    queryKey: ['messages', get(idAtom)],
    queryFn: async ({ queryKey: [, id] }) => {
      return await resolveInitialMessages(id as string | null);
    },
  }));

  const messagesAtom = atom<
    Message[] | Promise<Message[]>,
    [messages: Message[] | Promise<Message[]>],
    void
  >(
    (get) => {
      const messages = get(primitiveMessagesAtom);

      if (messages === null) {
        const resolvedMessages = get(initialMessagesAtom);

        if ('then' in resolvedMessages) {
          return [];
        }

        return resolvedMessages.data;
      }

      return messages;
    },
    (_get, set, messages) => {
      set(primitiveMessagesAtom, messages);
    }
  );

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions