Skip to content

Loading Remote Data

In FormCreate, the fetch property provides powerful functionality for loading data from remote APIs and applying it to form components. With flexible configuration, fetch can handle various scenarios, from simple option loading to complex dynamic data processing.

This feature is internally implemented through custom property methods.

Data Type

The following is the detailed type definition of the fetch property:

ts
type Fetch = {
  // API endpoint URL
  action: String;
  // Target property path where data will be inserted, e.g., 'options' or 'props.options'
  to?: String;
  // Pre-request callback; return false to cancel the request
  beforeFetch?: ( config: Object, rule:Rule, api:Api) => void|boolean|Promise;
  // Parse the API response and return the final data; defaults to `res.data`
  parse?: String | ((body: any, rule:Rule, api:Api) => any);
  // HTTP request method, defaults to 'GET'
  method?: String;
  // URL query parameters
  query?: Object;
  // Request body data
  data?: Object;
  // Request body format, either 'json' or 'formData' (default)
  dataType?: 'json' | 'formData';
  // Custom HTTP request headers
  headers?: Object;
  // Error callback when the request fails
  onError?: (e: Error | ProgressEvent) => void;
 }

Note

To send the request body as JSON, set dataType to 'json'.

Override Built-in Request Method

In some advanced scenarios, you may need to customize the request method. By overriding the formCreate.fetch method in the main.js file, you can define the request logic as needed.

js
const globalFetch = formCreate.fetch;
formCreate.fetch = (config) => {
    config.headers.token = getCookie('user-token');
    return globalFetch(config);
}

Note

File uploads also use the fetch method. Note that file uploads have special requirements. For implementation details, see the Built-in Request Module.

Examples

Load Data from an API

Load Data Using a Custom Method

Send a POST Request

js
const rules = [
    {
        type: 'select',
        field: 'product',
        title: 'Select Product',
        fetch: {
            action: '/api/products',
            to: 'options',
            type: 'POST',
            dataType: 'json',
            data: {
                Authorization: 'Bearer your-auth-token'
            },
            parse: (res) => res.data.map(product => ({ label: product.name, value: product.id })),
            onError: (error) => console.error('Failed to load product data:', error)
        }
    }
]

Custom Request Headers

js
const rules = [
    {
        type: 'select',
        field: 'product',
        title: 'Select Product',
        fetch: {
            action: '/api/products',
            to: 'options',
            headers: {
                Authorization: 'Bearer your-auth-token'
            },
            parse: (res) => res.data.map(product => ({ label: product.name, value: product.id })),
            onError: (error) => console.error('Failed to load product data:', error)
        }
    }
]

Set Token Before Sending Request

Dynamically add an Authorization token to request headers before sending API requests.

js
// Configure global options for form creation
const formOptions = {
    // Hook before request is sent
    beforeFetch: (options) => {
        // Dynamically set Authorization token in request headers
        const token = 'your-auth-token'; // Token here can be obtained from any storage
        options.headers = {
            Authorization: `Bearer ${token}`
        };
    }
};
// Create form
const rules = [
    {
        type: 'select',
        field: 'product',
        title: 'Select Product',
        fetch: {
            action: '/api/products',
            to: 'options',
            parse: (res) => res.data.map(product => ({ label: product.name, value: product.id })),
            onError: (error) => console.error('Failed to load product data:', error)
        }
    }
];

Steps:

  1. Set global formOptions: Configure the global beforeFetch method to ensure this hook runs for all components that use fetch.

  2. Dynamically retrieve the token: In beforeFetch, retrieve the token from storage, Vuex, or other sources, then add it to the request headers.

  3. Create form and use fetch: When form components use fetch, the beforeFetch method will automatically run, attaching the Authorization token.

Override Built-in Request Method and Set Token

Automatically attach an Authorization token to request headers for all API requests to ensure every request includes valid authentication information.

In main.js:

js
import formCreate from '@form-create/element-ui'; // Assume using Element UI


const globalFetch = formCreate.fetch;
// Override formCreate's built-in fetch method
formCreate.fetch = (config) => {
    // Get or generate the token
    const token = 'your-auth-token'; // You can retrieve the token from Vuex, localStorage, or elsewhere
    // Set request headers and attach the Authorization token
    config.headers = {
        ...config.headers,
        Authorization: `Bearer ${token}`,
    };
    return globalFetch(config);
};


// Create form
const api = formCreate.create([
    {
        type: 'select',
        field: 'product',
        title: 'Select Product',
        fetch: {
            action: '/api/products',
            to: 'options',
            parse: (res) => res.data.map(product => ({ label: product.name, value: product.id })),
            onError: (error) => console.error('Failed to load product data:', error),
        },
    },
], {
    // Other form configurations
});

Steps:

  1. Override the fetch method: During initialization, override formCreate.fetch to ensure all requests use your custom method.

  2. Set the Authorization token: For each request, retrieve or generate the token from storage and attach it to the headers.

  3. Send the request and handle the response: Based on the method, action, data, and other parameters in the options, send the request and process the response data.

FormCreate is an open-source project released under the MIT License. Free for personal and commercial use.