Skip to main content

Data State Management

Data state management is a crucial part of building dynamic Mapples applications. This guide covers how to work with data in your Mapples projects, including adding mock data, using uploaded state, and passing data to your Mapplets.


Adding Mock Data in Mapples Creator

When developing your application, you'll often need to work with sample data to design and test your interfaces. Mapples Creator makes it easy to add mock data directly in the visual editor.

How to Add Mock Data

Adding Mock Data

Screenshot showing the process of adding mock data in Mapples Creator interface

To add mock data in Mapples Creator:

  1. Open the Data Panel - Navigate to the data section in the creator interface
  2. Create Data Structure - Define your data schema with the required fields
  3. Add Sample Values - Fill in realistic sample data for testing and design
  4. Preview Changes - See how your mock data affects your component rendering
💡 Pro Tip

Use realistic mock data that matches your production data structure. This helps identify potential UI issues early in the development process.


Using Uploaded State

Mapples Creator allows you to upload and use real data from external sources, making it easier to design with production-like data.

Working with Uploaded State

Using Uploaded State

Screenshot demonstrating how to use uploaded state data in Mapples Creator

To work with uploaded state:

  1. Upload Data File - Import JSON, CSV, or other supported data formats
  2. Map Data Fields - Connect your uploaded data to component properties
  3. Configure Bindings - Set up dynamic data bindings for your UI elements
  4. Test Integration - Verify that your components render correctly with real data
📝 Supported Formats

Mapples Creator supports various data formats including JSON, CSV, and API responses. The platform automatically detects data structure and suggests appropriate mappings.


Passing Data to Mapplets

Once you have your data structure defined, you can pass it to your Mapplets (Mapples components) using the state management system.

Basic Data Passing

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

// Define your application state
const appState = {
user: {
name: 'John Doe',
email: 'john@example.com',
preferences: {
theme: 'light',
language: 'en'
}
},
navigation: {
currentScreen: 'home',
history: []
},
content: {
title: 'Welcome to Mapples',
description: 'Build amazing apps with ease'
}
};

export default function HomeScreen() {
return (
<View style={styles.container}>
<HomeMapplet
state={appState}
/>
</View>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
});

Passing API Data to Mapplets

In real-world applications, you'll often need to fetch data from APIs and pass it to your Mapplets. This section demonstrates how to integrate API calls with Mapples state management.

Basic API Integration

Here's how to fetch data from an API and pass it to your Mapplets:

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

// Define the shape of your API response
interface UserData {
id: number;
name: string;
email: string;
profile: {
avatar: string;
bio: string;
location: string;
};
}

interface ApiResponse {
user: UserData;
posts: Array<{
id: number;
title: string;
content: string;
createdAt: string;
}>;
}

export default function HomeScreen() {
const [appState, setAppState] = useState({
user: null,
posts: [],
loading: true,
error: null
});

// Fetch data from API
useEffect(() => {
const fetchUserData = async () => {
try {
setAppState(prev => ({ ...prev, loading: true, error: null }));

// Make API call
const response = await fetch('https://api.example.com/user/profile');

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const data: ApiResponse = await response.json();

// Update state with API data
setAppState({
user: data.user,
posts: data.posts,
loading: false,
error: null
});

} catch (error) {
setAppState(prev => ({
...prev,
loading: false,
error: error instanceof Error ? error.message : 'An error occurred'
}));
}
};

fetchUserData();
}, []);

// Show loading state
if (appState.loading) {
return (
<View style={[styles.container, styles.centered]}>
<ActivityIndicator size="large" color="#DB5A42" />
<Text style={styles.loadingText}>Loading user data...</Text>
</View>
);
}

// Show error state
if (appState.error) {
return (
<View style={[styles.container, styles.centered]}>
<Text style={styles.errorText}>Error: {appState.error}</Text>
</View>
);
}

// Render Mapplet with API data
return (
<View style={styles.container}>
<HomeMapplet
state={appState}
onAction={(action) => {
console.log('Action received:', action);
// Handle actions that might trigger new API calls
}}
/>
</View>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
centered: {
justifyContent: 'center',
alignItems: 'center',
},
loadingText: {
marginTop: 10,
fontSize: 16,
color: '#666',
},
errorText: {
fontSize: 16,
color: '#DB5A42',
textAlign: 'center',
paddingHorizontal: 20,
},
});

Advanced API Integration with Multiple Endpoints

For complex applications, you might need to fetch data from multiple API endpoints:

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

export default function DashboardScreen() {
const [appState, setAppState] = useState({
user: null,
notifications: [],
analytics: null,
settings: null,
loading: {
user: true,
notifications: true,
analytics: true,
settings: true,
},
errors: {}
});

useEffect(() => {
// Fetch multiple data sources concurrently
const fetchAllData = async () => {
const endpoints = [
{ key: 'user', url: 'https://api.example.com/user' },
{ key: 'notifications', url: 'https://api.example.com/notifications' },
{ key: 'analytics', url: 'https://api.example.com/analytics' },
{ key: 'settings', url: 'https://api.example.com/settings' },
];

// Create promises for all API calls
const promises = endpoints.map(async ({ key, url }) => {
try {
const response = await fetch(url, {
headers: {
'Authorization': 'Bearer YOUR_API_TOKEN',
'Content-Type': 'application/json',
},
});

if (!response.ok) {
throw new Error(`Failed to fetch ${key}: ${response.status}`);
}

const data = await response.json();

// Update state for successful fetch
setAppState(prev => ({
...prev,
[key]: data,
loading: { ...prev.loading, [key]: false }
}));

} catch (error) {
// Update state for failed fetch
setAppState(prev => ({
...prev,
loading: { ...prev.loading, [key]: false },
errors: {
...prev.errors,
[key]: error instanceof Error ? error.message : 'Unknown error'
}
}));
}
});

// Wait for all promises to complete
await Promise.allSettled(promises);
};

fetchAllData();
}, []);

return (
<View style={styles.container}>
<HomeMapplet
state={appState}
onAction={async (action) => {
// Handle actions that might require API calls
if (action.type === 'REFRESH_DATA') {
// Trigger a data refresh
setAppState(prev => ({
...prev,
loading: {
user: true,
notifications: true,
analytics: true,
settings: true,
}
}));

// Re-fetch data (you could extract the fetch logic into a reusable function)
} else if (action.type === 'UPDATE_SETTINGS') {
try {
const response = await fetch('https://api.example.com/settings', {
method: 'PUT',
headers: {
'Authorization': 'Bearer YOUR_API_TOKEN',
'Content-Type': 'application/json',
},
body: JSON.stringify(action.payload),
});

if (response.ok) {
const updatedSettings = await response.json();
setAppState(prev => ({ ...prev, settings: updatedSettings }));
}
} catch (error) {
console.error('Failed to update settings:', error);
}
}
}}
/>
</View>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
});

Best Practices for API Integration

🚀 Performance Tips
  • Concurrent Fetching: Use Promise.allSettled() for multiple independent API calls
  • Caching: Implement caching strategies to avoid unnecessary API requests
  • Pagination: Handle paginated responses for large datasets
  • Optimistic Updates: Update UI immediately for better user experience
⚠️ Error Handling
  • Always handle network errors and API failures gracefully
  • Provide meaningful error messages to users
  • Implement retry logic for transient failures
  • Use loading states to indicate ongoing operations
📝 State Management
  • Structure your state to separate API data from UI state
  • Use TypeScript interfaces to define API response shapes
  • Keep loading and error states for each API endpoint
  • Consider using state management libraries for complex scenarios

What's Next?

📊 @mapples/state Documentation

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

Explore State API →

🧩 Mapplets Tutorial

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

Mapplets →