Calling an action
Prerequisites
Read the creating a Frontend component article.
To trigger an operation on a backend system or fetch data asynchronously after initial rendering, call an action extension. For more information, see Developing an action extension.
For this example, we'll use the following Frontend component to implement searching a backend data set using an action:
import React from 'react';const CharacterSearchTastic: React.FC = () => {return (<><formonSubmit={(event) => {event.preventDefault();}}><label>Search:<input type="text" name="search" /></label><input type="submit" value="Search" /></form><ul></ul></>);};export default CharacterSearchTastic;
{"tasticType": "example/character-search","name": "Character search","category": "Example","description": "A frontend component showing actions and session handling","schema": []}
The Frontend component doesn't provide any configuration to the Studio and only renders a rudimentary search form and an empty list.
Perform the fetch call
An action extension is a server function in the API hub that can be invoked by a URL in the following format: https://<frontastic-host>/frontastic/action/<namespace>/<action>
. For more information about action endpoints, see Action.
To communicate with your custom action extensions, use the frontend SDK's callAction
method as it automatically resolves the correct API hub host for you, maintains the session, and provides other configuration options.
import { sdk } from 'sdk';export const characterSearch = async (search: string) => {sdk.callAction({actionName: 'star-wars/character',query: { search: encodeURIComponent(search) },}).then((response) => {setResults(response.data.allPeople.people);});};
Sending custom headers
You can send only the coFE-Custom-Configuration
custom header with your request to the API hub; all other custom headers are ignored by the API hub. You can pass a string value to this header using the SDK's callAction
customHeaderValue
parameter, as demonstrated in the following example:
import { sdk } from 'sdk';export const characterSearch = async (search: string) => {return await sdk.callAction({actionName: 'star-wars/character',query: { search: encodeURIComponent(search) },customHeaderValue: 'header-value-as-string',}).then((response) => {setResults(response.data.allPeople.people);});};