Skip to content
Brandon Jordan edited this page Oct 30, 2024 · 24 revisions

Busy State

Almost all HTTP objects in Spark have a busy property with a Store as the value so that their busy state can be modeled.

Fetch Store

A FetchStore extends a store and models its value on the response from the provided URL using the native Fetch API.

const posts = new FetchStore("http://example.com/api/v1/posts", initialValue = {});

This will fetch the URL provided with fetch() and set the value of the store to the JSON response.

posts.fetch();

Extending Fetch Store

Extending the FetchStore is recommended for loading page content.

This allows you to automatically fetch in the constructor if desired. This isn't done automatically in the base FetchStore, as only loading HTTP resources when they are used can make for more performant code, but may not be practical for all use cases.

class Articles extends FetchStore {
    constructor() {
        super('https://example.com/api/v1/articles');
        this.fetch();
    }
}

Various page content may be expected to load almost immediately and this can lead to fetch()-fatigue if called outside the constructor.

Response Handling

You can optionally custom handle the response before it is set on the store by overriding onResponse().

class Articles extends FetchStore {
    constructor() {
        super('https://example.com/api/v1/articles');
        this.fetch();
    }

    onResponse(data) {
        // Transform data then return...
        return data;
    }
}

Error Handling

To catch errors and add additional methods for an API endpoint response. Spark sets a method to override called onError(), which is called when an error is caught in the request.

class Articles extends FetchStore {
    constructor() {
        super('https://example.com/api/v1/articles');
        this.fetch();
    }

    onError(err) {
        // handle error
    }
}
Clone this wiki locally