While useAction
is commonly used with forms, there are advanced scenarios where you might need more flexible control over when and how actions are triggered. This approach is useful when you need to perform additional logic or transformations before executing the action.
Here's an example of how to use useAction
with direct execution:
Greeting.tsx actions.ts
import { useAction } from '@vergestack/api-react' ;
import { greetingAction } from './actions' ;
export function GreetingComponent () {
const { data , errors , execute } = useAction (greetingAction);
const [ name , setName ] = useState ( '' );
return (
<>
< input
name = "name"
value = {name}
onChange = {( e ) => setName (e.target.value)}
/>
< button onClick = {() => execute (name)}>Greet</ button >
{data && < p >Data: {data}</ p >}
{errors && < p >Errors: {errors. join ( ', ' )}</ p >}
</>
);
}
In this example, the execute
function is called directly when the button is clicked, passing the name
state as an argument.
Direct execution allows for more complex scenarios, such as:
Performing data transformations before execution
Conditional execution based on certain criteria
Executing based on non-form based interactions, such as infinite scroll event triggers
Here's an example that demonstrates some of these advanced use cases:
import { useAction } from '@vergestack/api-react' ;
import { greetingAction } from './actions' ;
import { useState } from 'react' ;
export function ComplexGreetingComponent () {
const { data , errors , execute , isPending } = useAction (greetingAction);
const [ name , setName ] = useState ( '' );
const handleGreet = async () => {
// Data transformation
const formattedName = name. trim (). toLowerCase ();
// Conditional execution
if (formattedName. length > 0 ) {
// Execute the greeting action
await execute (formattedName);
}
};
return (
<>
< input value = {name} onChange = {( e ) => setName (e.target.value)} />
< button onClick = {handleGreet}>Greet</ button >
{isPending && < p >Pending...</ p >}
{data && < p >Greeting: {data}</ p >}
{errors && < p >Errors: {errors. join ( ', ' )}</ p >}
</>
);
}
This example demonstrates how advanced usage allows for more complex logic, including data transformation and conditional execution.
For more information on the available properties and methods, check out the API Reference page.