Client API response within a plugin

Hi There! Doeas anyone know how to fetch the response when doing a client side api request when building a plugin? I get the respons succesfully in devtools, but just can’t seem to capture it within my JS:

function(properties, context) {
// This function is used to wrap asynchronous operations and handle the callback
return context.async(callback => {
// Function to make the API call
async function triggerClientApiCall(apiEndpoint, method, jsonData, headersArray) {
// Transform the array of key/value pairs into an object for headers
const headers = headersArray.reduce((acc, header) => {
acc[header.key] = header.value;
return acc;
}, {});

        // Prepare the options for the fetch call
        const options = {
            method: method,
            headers: headers
        };

        // Add the JSON data to the body if the method is not GET
        if (method !== 'GET' && jsonData) {
            options.body = jsonData; // jsonData should be a JSON string
        }

        // Perform the fetch call and handle the response
        try {
            const response = await fetch(apiEndpoint, options);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const responseBody = await response.json(); // Adjust this if the response is not JSON
            callback(null, responseBody); // No error, pass the response body to the callback
        } catch (error) {
            // Log and pass any errors encountered during the fetch to the callback
            console.error('API call error:', error);
            callback(error.toString()); // Pass the error to the callback
        }
    }

    // Extract properties
    const apiEndpoint = properties.api_endpoint;
    const method = properties.method;
    const jsonData = properties.json_data; // This should be a JSON string
    const headersArray = properties.headers; // Assumed to be an array of objects

    // Trigger the API call and handle it with the context.async callback
    triggerClientApiCall(apiEndpoint, method, jsonData, headersArray);
});

}

client side actions don’t return values. The usual workaround is to publish a state and then trigger an event, and at that point there is little value in using context.async

2 Likes

I see, thank you for your reply!

1 Like