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

infinity loading #11

Open
himself65 opened this issue May 15, 2024 · 0 comments
Open

infinity loading #11

himself65 opened this issue May 15, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@himself65
Copy link
Member

himself65 commented May 15, 2024

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);
    }
  );
@himself65 himself65 added the bug Something isn't working label May 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant