Calling an action

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:

Implementing the character search Frontend componenttypescript
import React from 'react';
const CharacterSearchTastic: React.FC = () => {
return (
<>
<form
onSubmit={(event) => {
event.preventDefault();
}}
>
<label>
Search:
<input type="text" name="search" />
</label>
<input type="submit" value="Search" />
</form>
<ul></ul>
</>
);
};
export default CharacterSearchTastic;
Character search Frontend component schemajson
{
"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 sdk.callAction() method, as it automatically resolves the correct API hub host for you and maintains the session.

Implementing the character search action calltypescript
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 only send the coFE-Custom-Configuration custom header with your request to the API hub; all other custom headers are ignored by the API hub.

An example of sending custom headers to actionsTypeScript
import { sdk } from 'sdk';
export const characterSearch = async (search: string) => {
return await sdk
.callAction({
actionName: 'star-wars/character',
query: { search: encodeURIComponent(search) },
serverOptions: {
req: {
method: 'POST',
headers: { 'coFE-Custom-Configuration': 'header-value-as-string' },
},
},
})
.then((data) => {
setResults(data.data.allPeople.people);
});
};