aws-amplify / amplify-js

A declarative JavaScript library for application development using cloud services.
https://docs.amplify.aws/lib/q/platform/js
Apache License 2.0
9.43k stars 2.13k forks source link

Native support or docs for Tanstack React Query/Orval #12792

Open straygar opened 10 months ago

straygar commented 10 months ago

Environment information

-

Description

Orval is a wrapper around Tanstack React Query, auto-generated from an OpenAPI spec.

It would be fantastic and lead to much cleaner React Web & Native code if we could auto-generate hooks to access our data and manage loading, error states, instead of manually having to deal with useEffect and useState.

Here is what it would look like with an Orval-like interface:

import { useGetBookDetails } from '@/...';

interface Props {
  bookId: string;
}

export const MyComponent = ({ bookId }: Props) => {
  const { data: bookDetails, isLoading, error } = useGetBookDetails({ bookId });

  return (<>
    {isLoading && <Loader />}
    {error && <span style={{ color: 'red' }}>{error.message}</span>}
    {bookDetails && <h2>{bookDetails.title}</h2>}
  </>);
}

Although something like this could also work and would avoid code generation:

interface Props {
  bookId: string;
}

export const MyComponent = ({ bookId }: Props) => {
  const { data: bookDetails, isLoading, error } = useQuery(
    () => client.models.Book.get({ id: bookId });
  );

  return (<>
    {isLoading && <Loader />}
    {error && <span style={{ color: 'red' }}>{error.message}</span>}
    {bookDetails && <h2>{bookDetails.title}</h2>}
  </>);
}
ykethan commented 10 months ago

Hey,👋 thanks for raising this! I'm going to transfer this over to our JS repository for better assistance 🙂.

nadetastic commented 10 months ago

Hi @straygar thanks for opening this issue. Regarding using TanStack Query with the JS library, have you had a chance to look at the documentation here?

straygar commented 10 months ago

Yup, sure have! The docs say (if I understand correctly) that you should write a react-query wrapper for every API operation, but I wonder if we can provide a generic wrapper, especially given the new magical Data API in Gen2:

const { data, errors } = client.models.Book.list({
  filters: ...
});

I assume this should be possible, based on the zod-like data model schema you can now define in your data/resource.ts file.