Fetching Data and API Calls

TargetJS integrates API requests directly into its target execution system. Use the special fetch target to retrieve data with GET or send data with POST. You can also call fetch() from a regular target. The response becomes available through val(targetName), where targetName is the name of the target that initiated the request. Dependent targets with $ or $$ can use the results to update the interface, create children, or start animations.

Use cycles, loop, and interval to repeat requests and control their timing. Use instances or arrays of URLs to send multiple requests in parallel. You can chain dependent targets to coordinate further actions, or handle updates and responses through callbacks such as onUpdate, onValueChange, onSuccess, onError, and onComplete.

Results from multiple requests retain their original request positions, even when responses arrive out of order. Dependent targets therefore read results in request order.

Basic API Request

This example uses the fetch target to retrieve a random user. Initially, the application displays "Loading...". When the request completes, the dependent html$$ target runs. On success, this.val('fetch') contains the returned user object, and html$$ displays its name.

To add callbacks, use the object form of the fetch target. The following example logs target updates, value changes, successful responses, and completion:

A successful request produces output like the following. The user details vary between requests:

onUpdate: undefined
onValueChange: {"id":"user_6b0921975ce15","name":"Frank Brown","email":"frank.brown@example.com"}
onSuccess: {"id":"user_6b0921975ce15","name":"Frank Brown","email":"frank.brown@example.com"}
onUpdate: {"id":"user_6b0921975ce15","name":"Frank Brown","email":"frank.brown@example.com"}
onComplete: {"id":"user_6b0921975ce15","name":"Frank Brown","email":"frank.brown@example.com"}

The first onUpdate runs when the target starts, before the response is available, so this.val('fetch') is still undefined. When the response arrives, TargetJS publishes the value and triggers onValueChange, followed by onSuccess. Another onUpdate reports the response update, and onComplete runs when the fetch target completes. The dependent html$$ target then displays the user's name.

Repeated API Requests and Dynamic Content

This example uses cycles: 5 and interval: 1000 to execute the fetch target five times. The first request starts immediately. Subsequent executions are scheduled one second apart. Requests can overlap when a response takes longer than the interval.

The card$ target processes one response at a time. Inside each card, this.parent.val('fetch') provides the response selected for that activation. Responses are selected in request order, even if they arrive in a different order.

Each card animates its width and scale. done$$ runs after all five responses have been processed and the preceding card animations have completed.

You can use instances: 5 to start five requests in one execution. You can also combine it with cycles to start repeated batches of parallel requests.

Reading API Responses

The value exposed by val('fetch') depends on whether the request is a batch and how its next dependent target runs.

Fetch configuration val('fetch') or val(targetName)
Single request The response payload.
Batch followed by a single $ target One response at a time based on request order.
Batch followed by a $$ target or regular targets An array of responses in request order.

Request Order Is Preserved

Suppose requests are started in the order 0, 1, 2, but their responses arrive in the order 2, 0, 1:

  • With $, the dependent target processes response 0, then response 1, then response 2. A response that arrives early waits for its turn and for the preceding activation to finish.
  • With $$, the dependent target receives [result0, result1, result2] after the batch and preceding target work complete.

Sending Data with POST

The fetch target uses GET by default. To send data with POST, provide a request configuration containing url, method, and data.

App({
        fetch: {
            value: {
                url: '/api/users',
                method: 'POST',
                data: { id: '12345' }
            },
            onError(response) {
                console.error(JSON.stringify(response));
            }
        }
    });

Starting Requests from a Regular Target

When a request needs to start inside a regular target, use fetch(). It registers the request with the currently executing target.

App({
        load() {
            fetch(this, 'https://targetjs.io/api/randomUser', { data: { id: 1 } });
        },
        html$() {
            return this.val('load').name;
        }
    });

The source target is named load in this example, so its response is read with val('load').

Documentation topics