Skip to main content

Handling Actions

Actions are the core mechanism for handling user interactions in Mapples. They allow you to respond to user input, update application state, and trigger various behaviors in your Mapplets.


What are Actions?

Actions in Mapples are event handlers that respond to user interactions such as button taps, form submissions, navigation events, and custom gestures. They bridge the gap between your UI components and your application logic.

📘 Key Concept

Actions are defined in Mapples Creator and automatically bound to your Mapplet components. When a user interacts with a UI element, the corresponding action is triggered in your application code.


Creating Actions in Mapples Creator

Step 1: Define Actions in Designer

In Mapples Creator, you can visually create and configure actions for your UI components:

Creating Actions in Mapples Creator Screenshot showing how to bind actions to components in Mapples Creator interface

💡 Pro Tip

Use descriptive action names that clearly indicate what the action does. This makes your code more maintainable and easier to debug.

Step 2: Configure Action Parameters

Actions can accept parameters that provide context about the user interaction:

Action Parameters Configuration Screenshot demonstrating how to configure action parameters in Mapples Creator


Implementing Actions in Your Code

Basic Action Handler

Here's how to implement basic action handling in your Mapplet:

import React from 'react';
import { Alert } from 'react-native';
import { MappletType } from '@mapples/types';
import ActionProvider from '@mapples/action';
import StateProvider from '@mapples/state';
import { RenderComponent } from '@mapples/render';

import { root } from './Home.json';

export type HomeMappletProps<T extends object> = MappletType<T> & {};

export default function HomeMapplet<State extends object = object>({
state,
onAction,
}: HomeMappletProps<State>) {

// Handle actions from Mapples Creator
const handleAction = (actionName: string, params?: any) => {
switch (actionName) {
case 'onButtonPress':
Alert.alert('Button Pressed', 'Hello from Mapples!');
break;

case 'onNavigate':
// Handle navigation
console.log('Navigating to:', params?.destination);
break;

case 'onFormSubmit':
// Handle form submission
console.log('Form data:', params?.formData);
break;

default:
// Pass action to parent component
onAction?.(actionName, params);
}
};

return (
<StateProvider state={state}>
<ActionProvider onAction={handleAction}>
<RenderComponent {...root} />
</ActionProvider>
</StateProvider>
);
}

Advanced Action Patterns

State Updates with Actions

Actions often need to update application state:

import React, { useState } from 'react';
import { View } from 'react-native';
import HomeMapplet from '../components/HomeMapplet';

export default function HomeScreen() {
const [appState, setAppState] = useState({
user: { name: 'John Doe', isLoggedIn: false },
counter: 0,
todos: []
});

const handleAppAction = (actionName: string, params?: any) => {
switch (actionName) {
case 'incrementCounter':
setAppState(prev => ({
...prev,
counter: prev.counter + 1
}));
break;

case 'addTodo':
setAppState(prev => ({
...prev,
todos: [...prev.todos, {
id: Date.now(),
text: params?.text || '',
completed: false
}]
}));
break;

case 'toggleTodo':
setAppState(prev => ({
...prev,
todos: prev.todos.map(todo =>
todo.id === params?.id
? { ...todo, completed: !todo.completed }
: todo
)
}));
break;

case 'loginUser':
setAppState(prev => ({
...prev,
user: { ...prev.user, isLoggedIn: true }
}));
break;
}
};

return (
<View style={{ flex: 1 }}>
<HomeMapplet
state={appState}
onAction={handleAppAction}
/>
</View>
);
}

Async Actions

Handle asynchronous operations like API calls:

const handleAsyncAction = async (actionName: string, params?: any) => {
switch (actionName) {
case 'fetchUserData':
try {
setAppState(prev => ({ ...prev, loading: true }));

const response = await fetch(`/api/users/${params?.userId}`);
const userData = await response.json();

setAppState(prev => ({
...prev,
user: userData,
loading: false
}));
} catch (error) {
setAppState(prev => ({
...prev,
error: 'Failed to fetch user data',
loading: false
}));
}
break;

case 'submitForm':
try {
setAppState(prev => ({ ...prev, submitting: true }));

const response = await fetch('/api/forms', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(params?.formData)
});

if (response.ok) {
setAppState(prev => ({
...prev,
message: 'Form submitted successfully!',
submitting: false
}));
}
} catch (error) {
setAppState(prev => ({
...prev,
error: 'Failed to submit form',
submitting: false
}));
}
break;
}
};

Action Types and Parameters

Common Action Types

Mapples supports various types of actions that you can configure in Mapples Creator:

✅ Button Actions
  • onPress - Basic button tap
  • onLongPress - Long press gesture
  • onDoublePress - Double tap gesture
📱 Navigation Actions
  • onNavigate - Screen navigation
  • onBack - Back navigation
  • onModal - Modal presentation
📝 Form Actions
  • onSubmit - Form submission
  • onValidate - Form validation
  • onFieldChange - Input field changes

Parameter Handling

Actions can receive various types of parameters:

const handleAction = (actionName: string, params?: {
// UI element information
componentId?: string;
componentType?: string;

// User input data
value?: any;
formData?: Record<string, any>;

// Navigation data
destination?: string;
routeParams?: Record<string, any>;

// Custom parameters
[key: string]: any;
}) => {
// Handle action based on parameters
console.log('Action:', actionName);
console.log('Parameters:', params);
};

Debugging Actions

Action Logging

Enable action logging for development:

const handleAction = (actionName: string, params?: any) => {
if (__DEV__) {
console.log('🎬 Action triggered:', actionName);
console.log('📦 Parameters:', params);
console.log('🕒 Timestamp:', new Date().toISOString());
}

// Your action handling logic here
};

Action Validation

Validate actions and parameters:

const handleAction = (actionName: string, params?: any) => {
// Validate action exists
const validActions = ['onButtonPress', 'onNavigate', 'onFormSubmit'];

if (!validActions.includes(actionName)) {
console.warn(`Unknown action: ${actionName}`);
return;
}

// Validate required parameters
if (actionName === 'onNavigate' && !params?.destination) {
console.error('Navigation action requires destination parameter');
return;
}

// Process valid action
switch (actionName) {
// ... your action cases
}
};

Best Practices

🚀 Performance

Keep Actions Fast Actions should execute quickly to maintain smooth user experience. For heavy operations, consider using async actions with loading states.

⚠️ Error Handling

Always Handle Errors Implement proper error handling for all actions, especially async operations. Show meaningful error messages to users.

📋 State Management

Update State Immutably Always create new state objects instead of modifying existing ones to ensure proper re-renders and avoid bugs.

✨ Testing

Test Your Actions Write unit tests for your action handlers to ensure they work correctly with different parameters and edge cases.


Action Examples by Use Case

E-commerce Actions

const handleEcommerceAction = (actionName: string, params?: any) => {
switch (actionName) {
case 'addToCart':
// Add product to shopping cart
break;

case 'removeFromCart':
// Remove product from cart
break;

case 'updateQuantity':
// Update product quantity
break;

case 'checkout':
// Navigate to checkout
break;
}
};

Social Media Actions

const handleSocialAction = (actionName: string, params?: any) => {
switch (actionName) {
case 'likePost':
// Toggle post like
break;

case 'sharePost':
// Share post to social platforms
break;

case 'addComment':
// Add comment to post
break;

case 'followUser':
// Follow/unfollow user
break;
}
};
const handleNavigationAction = (actionName: string, params?: any) => {
switch (actionName) {
case 'goToProfile':
navigation.navigate('Profile', { userId: params?.userId });
break;

case 'openSettings':
navigation.navigate('Settings');
break;

case 'showModal':
setModalVisible(true);
break;
}
};

What's Next?

📊 @mapples/action Documentation

Dive deeper into the state management library with comprehensive API documentation and advanced examples.

Explore Actions API →

🧩 Mapplets Tutorial

Learn how to create and customize Mapplets that work with your data state.

Mapplets →