platformplatform / PlatformPlatform

🚀 Pre-alpha state. A platform designed for building enterprise-grade, multi-tenant products using Azure, .NET, React, TypeScript, Infrastructure as Code, etc.
https://platformplatform.github.io
MIT License
250 stars 27 forks source link

Improve the ergonomics of data loading in the front-end #558

Closed raix closed 3 months ago

raix commented 3 months ago

Summary & Motivation

Wrap the openapi-fetch client as an easy to use client specific to React and PlatformPlatform.

Examples of usage

React hook: useApi - Simple

The hook can be used to simply get the data from the server, but also provides loading, success state and problem detail info like type / status / title / detail and errors compatible with React Aria Components validation in forms.

  const { data } = useApi("/api/account-management/users", {
    params: {
      query: {
        PageSize: 1
      }
    }
  });

React hook: useApi - Debounced fetching

For use with debounced search etc. and threshold of min 3 chars before fetching the result:

  const [subdomain, setSubdomain] = useState("");
  const { data: isSubdomainFree } = useApi(
    "/api/account-management/account-registrations/is-subdomain-free",
    {
      params: {
        query: { Subdomain: subdomain }
      }
    },
    {
      autoFetch: subdomain.length > 3,
      debounceMs: 500
    }
  );

Use with useFormState / useActionState

The action is passed to the Form component and errors can be passed directly to validationErrors:

  const [{ success, errors, data, title, message }, action, isPending] = useFormState(
    api.action("/api/account-management/account-registrations/start"),
    { success: null }
  );

  // ...

    <Form
      action={action}
      validationErrors={errors}
      validationBehavior="aria"
    >

Plain fetch

The result will always be the data and the api client throws ProblemDetailsError

  const result = await api.get("/api/account-management/account-registrations/is-subdomain-free",
    {
      params: {
        query: { Subdomain: subdomain }
      }
    });

Checklist

sonarcloud[bot] commented 3 months ago

Quality Gate Passed Quality Gate passed

Issues
3 New issues
0 Accepted issues

Measures
0 Security Hotspots
6.0% Coverage on New Code
0.0% Duplication on New Code

See analysis details on SonarCloud

sonarcloud[bot] commented 3 months ago

Please retry analysis of this Pull-Request directly on SonarCloud

sonarcloud[bot] commented 3 months ago

Quality Gate Passed Quality Gate passed

Issues
0 New issues
0 Accepted issues

Measures
0 Security Hotspots
4.1% Coverage on New Code
0.0% Duplication on New Code

See analysis details on SonarCloud