Skip to content

Frontend Data Fetching

The frontend templates provide utilities for making API calls with automatic authentication handling and response parsing. There are two main approaches depending on whether you need a component-based or hook-based solution.

WithFetch Component

The WithFetch component is the simplest way to fetch data. It automatically handles loading and error states:

tsx
return (
  <WithFetch<WeatherData> url={`/api/weather/${location}`}>
    {(data) => <WeatherCard data={data} />}
  </WithFetch>
);

When to use:

  • Simple data fetching with automatic loading/error handling
  • When you want the component to manage the fetch lifecycle
  • For data that doesn't need to be shared across components

useFetch Hook

The useFetch hook gives you more control over the fetch lifecycle. Use it with WithFuture to handle loading and error states:

tsx
const future = useFetch<WeatherData>(`/api/weather/${location}`);

return (
  <WithFuture future={future}>
    {(weather) => <WeatherCard data={weather} />}
  </WithFuture>
);

When to use:

  • When you need to trigger refetches or poll data
  • When the fetched data needs to be shared across multiple components
  • When you need more control over the fetch lifecycle

Platform Gateway Access

Frontend calls to the Platform Gateway only support principal access (on behalf of the authenticated user). Use useFetch with the gateway endpoint path:

tsx
const data = useFetch<WeatherData>(
  `/api/gw/weather/current.json${queryString}`,
);

Note: Only use the Gateway for APIs requiring authentication. Publicly accessible APIs should be called directly.

Authentication Flow

When an API call returns a 403 Forbidden status with a Location header, the fetchApi utility automatically handles authentication:

  1. The Location header is extracted from the response
  2. An authentication popup is opened at the provided URL
  3. The popup polls for completion (user authenticates or closes the popup)
  4. On success, the original API call is retried automatically
  5. On failure or timeout (5 minutes), an error is thrown

This flow works transparently — you don't need to add any special handling in your API call code.

Response Parsing

fetchApi automatically determines how to parse the response based on the Content-Type header:

  • application/json: Parsed as JSON and returned as the generic type T
  • All other content types: Returned as plain text

If you need to handle binary data or other response types, use the native fetch function directly for those specific cases.