Skip to content

Latest commit

 

History

History
650 lines (469 loc) · 15.5 KB

File metadata and controls

650 lines (469 loc) · 15.5 KB

Getting Started with Fynd Commerce App

Welcome to the Fynd Commerce App! This guide will help you understand the core concepts, setup requirements, and essential components needed to work with this React Native application.

Table of Contents

  1. Prerequisites
  2. Project Setup
  3. Project Renaming
  4. Core Architecture
  5. Polyfills and Web Compatibility
  6. FPI Event System
  7. Key Components
  8. Development Guidelines

Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js (v16 or higher)
  • React Native CLI
  • Xcode (for iOS development)
  • Android Studio (for Android development)
  • Yarn or npm

📚 Setup Guide: For detailed instructions on setting up your development environment, including Android Studio and Xcode configurations, see the Development Environment Setup Guide.

Project Setup

  1. Clone the repository

    git clone https://github.com/your-username/fynd-commerce-app.git
    cd fynd-commerce-app
  2. Install dependencies

    yarn install
    # or
    npm install
  3. Environment Configuration

    The app uses react-native-config for environment variable management. You need to set up your environment variables:

    # Copy the sample environment file
    cp .sampleenv .env

    Edit the .env file with your actual values. The sample file includes comprehensive examples and documentation:

    # .env
    APPLICATION_ID=your_application_id
    APPLICATION_TOKEN=your_application_token
    DOMAIN=your_domain

    Important Notes:

    • Never commit your .env file to version control
    • The .env file is already in .gitignore
    • Environment variables are typed in react-native-config.d.ts
    • After changing environment variables, you need to rebuild the app

Getting Access Token Using Client Credentials

To use the Fynd Commerce App, you'll need to obtain an access token using client credentials. This token is required for making Platform API calls.

Requirements

  • You've registered on the Fynd Platform and have access to any company.

Step 1: Retrieve Client Credentials

You can obtain your Client Id and Client Secret from the platform panel. Follow these steps:

  1. Log in to your Fynd Platform account
  2. Select a company - If you have access to any company, you'll see a screen to select one. Otherwise, it will open the Create Company form.
  3. Access the Dashboard - Select the company from the company list to open the Fynd Platform Dashboard.
  4. Navigate to Developers - Click on the "Developers" tab in the sidebar, which opens the APIs & SDKs page.
  5. Create a Client - Click on the "Clients" tab, then click "Create Client" and fill in the necessary details and permissions.
  6. Get Credentials - You can now check your client credentials here.

Step 2: Get an Access Token Using Client Credentials

To make a Platform API call, you need a valid access token. You can retrieve an access token using your client credentials.

Important Note: An access token obtained through the client credentials flow is limited to accessing data from the single company associated with the credentials used to generate it.

Step 3: Configure Your Environment

Once you have your client credentials and access token, update your .env file:

# .env
APPLICATION_ID=your_client_id
APPLICATION_TOKEN=your_access_token
DOMAIN=your_platform_domain
  1. iOS Setup (macOS only)

    cd ios
    pod install
    cd ..

    💡 Tip: For detailed iOS setup instructions, see the Development Environment Setup Guide.

  2. Android Setup

    Ensure you have Android Studio installed and configured:

    • Install Android Studio from developer.android.com
    • Set up Android SDK and environment variables
    • Create an Android Virtual Device (AVD) or connect a physical device
    • Ensure ANDROID_HOME environment variable is set

    💡 Tip: For detailed Android setup instructions, see the Development Environment Setup Guide.

  3. Verify Development Environment

    Before starting the development server, verify your setup:

    # Check if React Native CLI is installed
    npx react-native --version
    
    # Check if Metro bundler is available
    npx react-native start --help
    
    #Check if the development environment is setup correctly
    npx @react-native-community/cli doctor
  4. Start the development server

    yarn start
    # or
    npm start
  5. Run on device/simulator

    # iOS (macOS only)
    yarn ios
    
    # Android
    yarn android

    Note: Make sure you have a simulator/emulator running or a physical device connected before running these commands.

  6. Rebuild after environment changes

    If you modify environment variables (.env file), you need to rebuild the app:

    # For iOS
    cd ios && pod install && cd ..
    yarn ios
    
    # For Android
    cd android && ./gradlew clean && cd ..
    yarn android

Project Renaming

Use react-native-rename to rename your project:

# Stop all processes, then run:
npx react-native-rename@latest "YourNewAppName"

# Clean and rebuild:
cd android && ./gradlew clean && cd ..
cd ios && xcodebuild clean && cd ..
yarn install && cd ios && pod install && cd ..

Update Assets

Splash Screen (BootSplash):

  • Replace assets/bootsplash/logo.png with your logo
  • Update assets/bootsplash/logo@1.5x.png and logo@2x.png for different densities

App Icons:

  • iOS: Replace icons in ios/FyndCommerceApp/Images.xcassets/AppIcon.appiconset/
  • Android: Replace icons in android/app/src/main/res/mipmap-*/

Troubleshooting:

npx react-native start --reset-cache

Core Architecture

The Fynd Commerce App is built with a modular architecture that includes:

  • React Native for cross-platform mobile development
  • TypeScript for type safety
  • GraphQL for data fetching
  • Redux (via fdk-store) for state management
  • React Navigation for routing
  • WebView integration for hybrid functionality

Polyfills and Web Compatibility

Why Polyfills Are Required

The Fynd Commerce App uses fdk-store, which is tightly coupled with web APIs. Since React Native doesn't provide the same web environment as browsers, we need polyfills to ensure compatibility.

Polyfill Implementation

The polyfills are implemented in src/shared/utils/polyfill.ts and provide the following web APIs:

1. URL Polyfill

import 'react-native-url-polyfill/auto';

This polyfill provides URL parsing and manipulation functionality that's available in browsers but missing in React Native.

2. Window Object Polyfill

if (typeof global !== 'undefined' && typeof window === 'undefined') {
  global.window = global;
}

Creates a window object in the global scope for libraries that expect browser-like environment.

3. Location API Polyfill

window.location = {
  href: 'https://www.google.com',
  pathname: '/',
  search: '',
  assign: () => {},
  reload: () => {},
  replace: () => {},
};

Provides a mock location object with essential properties and methods.

4. Document API Polyfill

if (!window.document) {
  window.document = {
    createElement: () => ({style: {}}),
    getElementById: () => null,
    querySelector: () => null,
    addEventListener: () => {},
    removeEventListener: () => {},
    body: {
      appendChild: () => {},
    },
  };
}

Creates a minimal document object for DOM manipulation libraries.

Usage

The polyfills are automatically imported in the main application entry point:

// In your main App.tsx or index.js
import './src/shared/utils/polyfill';

FPI Event System

Overview

The FPI (Fynd Platform Integration) Event System provides a communication bridge between the native app and web components. It uses an EventEmitter pattern to handle various application events.

EventEmitter Implementation

The EventEmitter is implemented in the polyfill file and provides:

class EventEmitter {
  constructor() {
    this.events = {};
  }

  on(eventName, listener) {
    // Register event listener
  }

  once(eventName, listener) {
    // Register one-time event listener
  }

  off(eventName, listener) {
    // Remove event listener
  }

  emit(eventName, payload) {
    // Emit event with data
  }
}

FPI Global Object

The FPI system creates a global object accessible via window.FPI:

window.FPI = {
  event: new EventEmitter(),
  state: new Proxy(
    {},
    {
      get(target, prop) {
        return window.FPIState[prop.toString()];
      },
    },
  ),
};

Common Events

The FPI Event System handles various application events:

1. User Authentication Events

// User login
window.FPI.event.emit('user.login', {
  userId: 'user123',
  timestamp: Date.now(),
});

// User logout
window.FPI.event.emit('user.logout', {
  timestamp: Date.now(),
});

2. Cart Events

// Cart update
window.FPI.event.emit('cart.update', {
  items: [...],
  total: 1500,
  itemCount: 3,
});

// Cart clear
window.FPI.event.emit('cart.clear', {
  timestamp: Date.now(),
});

3. Navigation Events

// Page navigation
window.FPI.event.emit('navigation.change', {
  from: '/products',
  to: '/cart',
  timestamp: Date.now(),
});

4. WebView Events

// WebView navigation
window.FPI.event.emit('webview.navigation', {
  url: 'https://example.com',
  canGoBack: true,
});

Event Handling in Components

Listening to Events

import {useEffect} from 'react';

function MyComponent() {
  useEffect(() => {
    const handleUserLogin = data => {
      console.log('User logged in:', data);
    };

    const handleCartUpdate = data => {
      console.log('Cart updated:', data);
    };

    // Register event listeners
    window.FPI.event.on('user.login', handleUserLogin);
    window.FPI.event.on('cart.update', handleCartUpdate);

    // Cleanup on unmount
    return () => {
      window.FPI.event.off('user.login', handleUserLogin);
      window.FPI.event.off('cart.update', handleCartUpdate);
    };
  }, []);

  return <div>...</div>;
}

Emitting Events

function handleLogin() {
  // Emit login event
  window.FPI.event.emit('user.login', {
    userId: 'user123',
    email: 'user@example.com',
    timestamp: Date.now(),
  });
}

function handleAddToCart(product) {
  // Emit cart update event
  window.FPI.event.emit('cart.update', {
    action: 'add',
    product: product,
    timestamp: Date.now(),
  });
}

WebView Integration

The FPI Event System is particularly important for WebView integration:

// In WebView event handler
const handleWebViewMessage = event => {
  const {eventName, eventData} = JSON.parse(event.nativeEvent.data);

  switch (eventName) {
    case 'user.logout':
      // Handle logout from WebView
      window.FPI.event.emit('user.logout', eventData);
      break;
    case 'cart.update':
      // Handle cart update from WebView
      window.FPI.event.emit('cart.update', eventData);
      break;
  }
};

Key Components

1. FPI Provider

The FPI Provider manages the FPI client and provides it to the application:

import {FpiProvider} from './src/shared/providers/fpi-provider';

function App() {
  return (
    <FpiProvider fpiClient={fpiInstance}>
      <YourApp />
    </FpiProvider>
  );
}

2. Theme Provider

Manages application theming:

import {ThemeProvider} from './src/shared/providers/theme-provider';

function App() {
  return (
    <ThemeProvider>
      <YourApp />
    </ThemeProvider>
  );
}

3. WebView Provider

Handles WebView state and navigation:

import {WebViewProvider} from './src/shared/providers/web-view-provider';

function App() {
  return (
    <WebViewProvider>
      <YourApp />
    </WebViewProvider>
  );
}

Development Guidelines

1. TypeScript Usage

  • Always use TypeScript for new components
  • Define proper interfaces for props and state
  • Use strict type checking

2. Component Structure

component-name/
├── component-name.tsx
├── component-name.style.ts
├── component-name.type.ts
├── hooks/
│   └── use-component-name.tsx
└── README.md

3. Testing

  • Write unit tests for all components
  • Use Jest and React Native Testing Library
  • Test files should be in src/__tests__/

4. Styling

  • Use styled-components for styling
  • Follow the theme system for colors and spacing
  • Use the scale utility for responsive design

5. State Management

  • Use the FPI client for global state
  • Use React hooks for local state
  • Avoid prop drilling by using context providers

6. Navigation

  • Use React Navigation for routing
  • Define routes in src/app/constants/route-keys.ts
  • Use the navigation hooks for programmatic navigation

Troubleshooting

Common Setup Issues

  1. Metro Bundler Issues

    # Clear Metro cache
    npx react-native start --reset-cache
    
    # Or clear watchman cache
    watchman watch-del-all
  2. iOS Build Issues

    # Clean iOS build
    cd ios && xcodebuild clean && cd ..
    
    # Reinstall pods
    cd ios && pod deintegrate && pod install && cd ..
  3. Android Build Issues

verify your Android development environment setup

  npx @react-native-community/cli doctor
# Clean Android build
cd android && ./gradlew clean && cd ..

# Clear Android cache
cd android && ./gradlew cleanBuildCache && cd ..
  1. Environment Variable Issues

    • Ensure .env file is in the root directory
    • Check that environment variables are properly typed in react-native-config.d.ts
    • Rebuild the app after changing environment variables

Common Runtime Issues

  1. Polyfill Errors

    • Ensure polyfills are imported before any other imports
    • Check that all required web APIs are polyfilled
  2. FPI Event Issues

    • Verify that window.FPI is properly initialized
    • Check event listener registration and cleanup
    • Ensure events are emitted with correct data structure
  3. WebView Integration

    • Verify message format between native and WebView
    • Check event handler registration
    • Ensure proper navigation handling

Getting Help

  • Check the individual documentation files in the docs/ directory
  • Review test files for usage examples
  • Examine the actual implementation in src/shared/
  • Check the README files in component directories

Next Steps

After completing this guide, explore:

  1. Development Environment Setup - Complete setup for Android Studio and Xcode
  2. Development Quick Reference - Common commands and shortcuts
  3. Store Documentation - Learn about data management
  4. Navigation Documentation - Understand routing
  5. Theme Documentation - Customize the UI
  6. Sections Documentation - Build content sections

Happy coding! 🚀