🎭 Mock Data Guide

Index

  1. Available Data
  2. Using Mocks
  3. Data Structure
  4. Customizing Mocks
  5. Data Generators
  6. Transition to Real Data

Available Data

Location: mocks/data.ts

ExportTypeDescriptionCount
mockUserUserExample user1
mockCategoriesCategory[]Item categories6
mockItemsItem[]Example items/products6
mockStatsStatCard[]Dashboard statistics4
mockNotificationsNotification[]Example notifications3
mockActivitiesActivity[]Feed activities7
mockConversationsConversation[]Chat conversations5
mockMessagesMessage[]Example messages6
defaultSettingsSettingsDefault settings1

Using Mocks

Import Data

import {
  mockUser,
  mockItems,
  mockCategories,
  mockActivities,
  mockConversations,
  mockMessages,
  mockNotifications,
  mockStats,
  defaultSettings,
} from '@/mocks/data';

In Screens

// app/(tabs)/explore/index.tsx
import { mockItems, mockCategories } from '@/mocks/data';

export default function ExploreScreen() {
  const [items, setItems] = useState(mockItems);
  const [categories] = useState(mockCategories);

  return (
    <View>
      <CategoryList categories={categories} />
      <ItemGrid items={items} />
    </View>
  );
}

En Contextos

// contexts/AppContext.tsx
import { mockUser, mockNotifications, defaultSettings } from '@/mocks/data';

export const [AppProvider, useApp] = createContextHook(() => {
  const [user, setUser] = useState<User | null>(mockUser);
  const [notifications, setNotifications] = useState(mockNotifications);
  const [settings, setSettings] = useState(defaultSettings);
  
  // ...
});

Con React Query (Simulando API)

import { mockItems } from '@/mocks/data';

const itemsQuery = useQuery({
  queryKey: ['items'],
  queryFn: async () => {
    // Simular delay de red
    await new Promise(resolve => setTimeout(resolve, 500));
    return mockItems;
  },
});

Estructura de Datos

mockUser

export const mockUser: User = {
  id: '1',
  name: 'Alex Johnson',
  email: 'alex@example.com',
  avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=200&h=200&fit=crop&crop=face',
  bio: 'Product designer & developer. Love building beautiful apps.',
  createdAt: '2024-01-15T10:00:00Z',
};

mockCategories

export const mockCategories: Category[] = [
  { id: '1', name: 'Technology', icon: 'Cpu', color: Colors.primary, itemCount: 24 },
  { id: '2', name: 'Design', icon: 'Palette', color: Colors.secondary, itemCount: 18 },
  { id: '3', name: 'Business', icon: 'Briefcase', color: Colors.accent, itemCount: 32 },
  { id: '4', name: 'Health', icon: 'Heart', color: Colors.success, itemCount: 15 },
  { id: '5', name: 'Travel', icon: 'Plane', color: Colors.warning, itemCount: 21 },
  { id: '6', name: 'Food', icon: 'UtensilsCrossed', color: Colors.error, itemCount: 28 },
];

Iconos usados: Cpu, Palette, Briefcase, Heart, Plane, UtensilsCrossed (de lucide-react-native)


mockItems

export const mockItems: Item[] = [
  {
    id: '1',
    title: 'Modern UI Design System',
    description: 'A comprehensive design system for building beautiful mobile applications...',
    image: 'https://images.unsplash.com/photo-1558655146-9f40138edfeb?w=400&h=300&fit=crop',
    category: 'Design',
    tags: ['UI', 'Mobile', 'System'],
    rating: 4.8,
    price: 49.99,
    isFavorite: true,
    createdAt: '2024-01-20T10:00:00Z',
  },
  // ... 5 items más
];

Categorías incluidas: Design, Technology, Business, Health, Travel, Food


mockStats

export const mockStats: StatCard[] = [
  { id: '1', title: 'Total Views', value: '12.5K', change: 12.5, icon: 'Eye', color: Colors.primary },
  { id: '2', title: 'Revenue', value: '$4,320', change: 8.2, icon: 'DollarSign', color: Colors.success },
  { id: '3', title: 'New Users', value: '284', change: -3.1, icon: 'Users', color: Colors.secondary },
  { id: '4', title: 'Conversion', value: '3.2%', change: 1.8, icon: 'TrendingUp', color: Colors.accent },
];

mockActivities

export const mockActivities: Activity[] = [
  {
    id: '1',
    type: 'like',
    userName: 'Sarah Chen',
    userAvatar: 'https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=100',
    message: 'liked your post "Modern UI Design System"',
    image: 'https://images.unsplash.com/photo-1558655146-9f40138edfeb?w=100',
    createdAt: new Date(Date.now() - 5 * 60000).toISOString(), // 5 minutos atrás
  },
  // ... más actividades
];

Tipos incluidos: like, comment, follow, purchase, review, mention


mockConversations

export const mockConversations: Conversation[] = [
  {
    id: '1',
    name: 'Sarah Chen',
    avatar: 'https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=100',
    lastMessage: 'Sure, let me check that for you!',
    lastMessageTime: new Date(Date.now() - 5 * 60000).toISOString(),
    unreadCount: 2,
    isOnline: true,
  },
  // ... más conversaciones
];

mockMessages

export const mockMessages: Message[] = [
  {
    id: '1',
    text: 'Hey! How are you doing?',
    senderId: 'other',
    createdAt: new Date(Date.now() - 60 * 60000).toISOString(),
    status: 'read',
  },
  {
    id: '2',
    text: "I'm good, thanks! Working on the new project.",
    senderId: 'current-user',
    createdAt: new Date(Date.now() - 55 * 60000).toISOString(),
    status: 'read',
  },
  // ... más mensajes
];

mockNotifications

export const mockNotifications: Notification[] = [
  {
    id: '1',
    title: 'New follower',
    message: 'Sarah started following you',
    type: 'info',
    read: false,
    createdAt: '2024-01-22T14:30:00Z',
  },
  // ... más notificaciones
];

defaultSettings

export const defaultSettings: Settings = {
  notifications: true,
  darkMode: false,
  haptics: true,
  language: 'English',
  currency: 'USD',
};

Personalizando Mocks

Cambiar Datos de Usuario

// mocks/data.ts
export const mockUser: User = {
  id: '1',
  name: 'Tu Nombre',           // ← Cambiar
  email: 'tu@email.com',       // ← Cambiar
  avatar: 'URL_DE_TU_AVATAR',  // ← Cambiar
  bio: 'Tu biografía aquí',    // ← Cambiar
  createdAt: '2024-01-15T10:00:00Z',
};

Agregar Más Items

// mocks/data.ts
export const mockItems: Item[] = [
  // ... items existentes
  {
    id: '7',  // ← ID único
    title: 'Tu Nuevo Item',
    description: 'Descripción del item...',
    image: 'https://images.unsplash.com/photo-XXXXXX',
    category: 'Technology',  // ← Debe coincidir con una categoría
    tags: ['tag1', 'tag2'],
    rating: 4.5,
    price: 29.99,
    isFavorite: false,
    createdAt: new Date().toISOString(),
  },
];

Agregar Nuevas Categorías

// mocks/data.ts
export const mockCategories: Category[] = [
  // ... categorías existentes
  { 
    id: '7', 
    name: 'Mi Categoría',      // ← Nombre
    icon: 'Bookmark',          // ← Icono de Lucide
    color: '#FF5733',          // ← Color hex
    itemCount: 10,             // ← Cantidad de items
  },
];

Generadores de Datos

Generar Items Dinámicamente

// mocks/generators.ts
import { Item } from '@/types';
import { generateId } from '@/utils/helpers';

const categories = ['Technology', 'Design', 'Business', 'Health'];
const images = [
  'https://images.unsplash.com/photo-1558655146-9f40138edfeb',
  'https://images.unsplash.com/photo-1633356122544-f134324a6cee',
  // ... más URLs
];

export function generateItem(overrides?: Partial<Item>): Item {
  const category = categories[Math.floor(Math.random() * categories.length)];
  
  return {
    id: generateId(),
    title: `Item ${Math.random().toString(36).substring(7)}`,
    description: 'Lorem ipsum dolor sit amet...',
    image: images[Math.floor(Math.random() * images.length)] + '?w=400&h=300&fit=crop',
    category,
    tags: [category.toLowerCase()],
    rating: Math.round((3.5 + Math.random() * 1.5) * 10) / 10,
    price: Math.round(Math.random() * 100 * 100) / 100,
    isFavorite: Math.random() > 0.7,
    createdAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
    ...overrides,
  };
}

export function generateItems(count: number): Item[] {
  return Array.from({ length: count }, () => generateItem());
}

// Uso
const items = generateItems(20);

Generar Actividades

// mocks/generators.ts
const activityTypes: Activity['type'][] = ['like', 'comment', 'follow', 'purchase', 'review'];
const userNames = ['Sarah Chen', 'Mike Johnson', 'Emily Davis', 'James Wilson'];
const avatars = [
  'https://images.unsplash.com/photo-1494790108377-be9c29b29330',
  'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d',
  // ...
];

export function generateActivity(overrides?: Partial<Activity>): Activity {
  const type = activityTypes[Math.floor(Math.random() * activityTypes.length)];
  const userName = userNames[Math.floor(Math.random() * userNames.length)];
  
  const messages: Record<Activity['type'], string> = {
    like: 'liked your post',
    comment: 'commented on your post',
    follow: 'started following you',
    purchase: 'purchased your item',
    review: 'left a review',
    mention: 'mentioned you',
  };

  return {
    id: generateId(),
    type,
    userName,
    userAvatar: avatars[Math.floor(Math.random() * avatars.length)] + '?w=100',
    message: messages[type],
    createdAt: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
    ...overrides,
  };
}

Transición a Datos Reales

Patrón: Abstracción de Datos

// lib/data.ts
import { mockItems, mockCategories } from '@/mocks/data';

const USE_MOCK = __DEV__ || !process.env.EXPO_PUBLIC_API_URL;

export async function getItems(): Promise<Item[]> {
  if (USE_MOCK) {
    // Simular delay
    await new Promise(resolve => setTimeout(resolve, 300));
    return mockItems;
  }
  
  // Datos reales
  const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}/items`);
  return response.json();
}

export async function getCategories(): Promise<Category[]> {
  if (USE_MOCK) {
    await new Promise(resolve => setTimeout(resolve, 200));
    return mockCategories;
  }
  
  const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}/categories`);
  return response.json();
}

Uso con React Query

// hooks/useItems.ts
import { useQuery } from '@tanstack/react-query';
import { getItems } from '@/lib/data';

export function useItems() {
  return useQuery({
    queryKey: ['items'],
    queryFn: getItems,
  });
}

// En componentes - sin cambios necesarios
function ItemList() {
  const { data: items, isLoading } = useItems();
  
  if (isLoading) return <Skeleton />;
  
  return <FlatList data={items} ... />;
}

Variables de Entorno

# .env.development
EXPO_PUBLIC_USE_MOCKS=true

# .env.production
EXPO_PUBLIC_USE_MOCKS=false
EXPO_PUBLIC_API_URL=https://api.tuapp.com

Checklist de Mocks

  • Datos representativos del dominio real
  • IDs únicos para cada item
  • Fechas realistas (usar new Date())
  • Imágenes de calidad (Unsplash, Pexels)
  • Variedad en los datos (diferentes estados)
  • Tipos correctos según types/index.ts
  • Fácil transición a datos reales