skip to Main Content

Suppose we first check whether a resource is not loading like this:

    @if (!countriesResource.isLoading()) {
      <ul>
        @for (
          country of countriesResource.value(); 
          track country.name.official
        ) {
          <li>{{ country.name.official }}</li>
        }
      </ul>

If the resource is not loading, however has not initiated a request yet, is there a way to provide an initial value so that countriesResource.value() resolves to an initial value?

2

Answers


  1. Does the Angular resource API support adding an initial value for the resource

    Today no.

    But keep in mind that resource is an experimental API and the Angular team plan to have an RFC on the concept of resource in the following week.

    Login or Signup to reply.
  2. Yes, you can provide an initial value for countriesResource.value() when the resource hasn’t initiated a request yet. This is typically achieved by setting a default value for the resource before the request is made. Here’s how you can structure your logic depending on your framework or implementation:

    Example with Default Value

    Assume countriesResource supports a way to set an initial value, such as countriesResource.value or a similar method:

    const countriesResource = createResource(() => fetchCountries(), {
      initialValue: [], // Set an initial value
    });
    

    Now your rendering logic remains safe because the initial value guarantees

    If the resource doesn’t natively support an initialValue or you cannot modify the resource directly, you can introduce a fallback value dynamically:

    const countries = countriesResource.value() || [];
    

    And modify your conditional rendering:

    @if (!countriesResource.isLoading()) {
    <ul>
    @for (
      country of (countriesResource.value() || []); 
      track country.name.official
    ) {
      <li>{{ country.name.official }}</li>
    }
    

    }

    Summary

    Providing an initial value ensures that your UI doesn’t break while waiting for data. Most resource-handling libraries or frameworks provide mechanisms for setting an initial state (initialValue, defaultValue, etc.) or allow you to handle it programmatically using fallbacks.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search