npm package: @pratik.vekariya1/react-native-sdk
Description: A React Native SDK with TypeScript
Latest version: 1.0.4

# @pratik.vekariya1/react-native-sdk

A comprehensive React Native SDK providing essential utilities and components for mobile app development.

## 📱 Features

- ✨ Easy integration with React Native projects
- 🚀 Optimized performance for both iOS and Android
- 📦 Lightweight and modular architecture
- 🔧 TypeScript support
- 🎯 Zero dependencies core functionality
- 📱 Cross-platform compatibility

## 📋 Installation

### Using npm
```bash
npm install @pratik.vekariya1/react-native-sdk
```

### Using yarn
```bash
yarn add @pratik.vekariya1/react-native-sdk
```

### Using pnpm
```bash
pnpm add @pratik.vekariya1/react-native-sdk
```

## 🔧 Integration Guide

### Step 1: Install the Package

Choose your preferred package manager:

```bash
# NPM
npm install @pratik.vekariya1/react-native-sdk

# Yarn
yarn add @pratik.vekariya1/react-native-sdk

# PNPM
pnpm add @pratik.vekariya1/react-native-sdk
```

### Step 2: Platform Setup

#### iOS Setup
1. Navigate to iOS directory and install pods:
```bash
cd ios && pod install && cd ..
```

2. For iOS 9+ support, add this to your `ios/Podfile`:
```ruby
platform :ios, '11.0'
```

3. If you encounter build issues, clean and rebuild:
```bash
npx react-native clean
cd ios && xcodebuild clean && cd ..
```

#### Android Setup
1. Ensure your `android/build.gradle` has minimum SDK version:
```gradle
buildscript {
    ext {
        minSdkVersion = 21
        compileSdkVersion = 33
        targetSdkVersion = 33
    }
}
```

2. Add to `android/app/build.gradle` if needed:
```gradle
android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
```

### Step 3: Initialize the SDK

#### Option A: Initialize in App.js/App.tsx (Recommended)
```javascript
import React, { useEffect } from 'react';
import { initializeSDK } from '@pratik.vekariya1/react-native-sdk';

const App = () => {
  useEffect(() => {
    // Initialize SDK when app starts
    initializeSDK({
      apiKey: 'your-api-key-here',
      environment: 'production', // or 'development'
      debugMode: __DEV__, // Enable debug in development
    });
  }, []);

  return (
    // Your app content
  );
};

export default App;
```

#### Option B: Initialize in index.js (Early initialization)
```javascript
import { AppRegistry } from 'react-native';
import { initializeSDK } from '@pratik.vekariya1/react-native-sdk';
import App from './App';
import { name as appName } from './app.json';

// Initialize SDK before app registration
initializeSDK({
  apiKey: 'your-api-key-here',
  environment: 'production',
});

AppRegistry.registerComponent(appName, () => App);
```

### Step 4: Basic Implementation

#### Using Hooks (Recommended)
```javascript
import React, { useState } from 'react';
import { View, Button, Text, Alert } from 'react-native';
import { useSDK } from '@pratik.vekariya1/react-native-sdk';

const MyComponent = () => {
  const { isReady, error, performAction } = useSDK();
  const [result, setResult] = useState(null);

  const handleAction = async () => {
    try {
      const data = await performAction('some-parameter');
      setResult(data);
      Alert.alert('Success', 'Action completed successfully');
    } catch (err) {
      Alert.alert('Error', err.message);
    }
  };

  if (!isReady) {
    return <Text>SDK Loading...</Text>;
  }

  if (error) {
    return <Text>SDK Error: {error.message}</Text>;
  }

  return (
    <View>
      <Button title="Perform SDK Action" onPress={handleAction} />
      {result && <Text>Result: {JSON.stringify(result)}</Text>}
    </View>
  );
};

export default MyComponent;
```

#### Using Components
```javascript
import React from 'react';
import { View, StyleSheet } from 'react-native';
import { SDKComponent } from '@pratik.vekariya1/react-native-sdk';

const MyScreen = () => {
  const handleSuccess = (data) => {
    console.log('SDK Success:', data);
    // Handle successful operation
  };

  const handleError = (error) => {
    console.error('SDK Error:', error);
    // Handle error
  };

  return (
    <View style={styles.container}>
      <SDKComponent
        onSuccess={handleSuccess}
        onError={handleError}
        style={styles.sdkComponent}
        // Additional props based on your SDK
        config={{
          theme: 'light',
          customOption: true
        }}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
  },
  sdkComponent: {
    height: 200,
    borderRadius: 8,
  },
});

export default MyScreen;
```

### Step 5: Environment Configuration

#### Development Environment
```javascript
// config/development.js
export const SDK_CONFIG = {
  apiKey: 'dev-api-key',
  environment: 'development',
  debugMode: true,
  baseURL: 'https://dev-api.yourservice.com',
  timeout: 30000,
};
```

#### Production Environment
```javascript
// config/production.js
export const SDK_CONFIG = {
  apiKey: 'prod-api-key',
  environment: 'production',
  debugMode: false,
  baseURL: 'https://api.yourservice.com',
  timeout: 10000,
};
```

#### Using Environment Config
```javascript
import { SDK_CONFIG } from './config/development'; // or production
import { initializeSDK } from '@pratik.vekariya1/react-native-sdk';

initializeSDK(SDK_CONFIG);
```

## 🚀 Quick Start Examples

## 📱 Complete Integration Examples

### Example 1: E-commerce App Integration
```javascript
// screens/ProductScreen.js
import React, { useState, useEffect } from 'react';
import { View, ScrollView, Text, StyleSheet, Alert } from 'react-native';
import { SDKManager, useSDKData } from '@pratik.vekariya1/react-native-sdk';

const ProductScreen = ({ route }) => {
  const { productId } = route.params;
  const [loading, setLoading] = useState(false);
  
  // Using SDK hook for data fetching
  const { data, loading: sdkLoading, error } = useSDKData('products', {
    productId,
    includeRecommendations: true
  });

  const handlePurchase = async () => {
    setLoading(true);
    try {
      const result = await SDKManager.processPayment({
        productId,
        userId: 'current-user-id',
        amount: data.price
      });
      
      Alert.alert('Success', 'Purchase completed successfully!');
    } catch (error) {
      Alert.alert('Error', error.message);
    } finally {
      setLoading(false);
    }
  };

  if (sdkLoading) return <Text>Loading product...</Text>;
  if (error) return <Text>Error: {error.message}</Text>;

  return (
    <ScrollView style={styles.container}>
      <Text style={styles.title}>{data.name}</Text>
      <Text style={styles.price}>${data.price}</Text>
      {/* Your UI components */}
    </ScrollView>
  );
};
```

### Example 2: Authentication Flow
```javascript
// components/AuthScreen.js
import React, { useState } from 'react';
import { View, TextInput, Button, Alert } from 'react-native';
import { SDKAuth } from '@pratik.vekariya1/react-native-sdk';

const AuthScreen = ({ navigation }) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = async () => {
    try {
      const authResult = await SDKAuth.signIn({
        email,
        password,
        rememberMe: true
      });

      // Store auth token
      await SDKAuth.storeToken(authResult.token);
      
      // Navigate to main app
      navigation.replace('HomeScreen');
    } catch (error) {
      Alert.alert('Login Failed', error.message);
    }
  };

  const handleSocialLogin = async (provider) => {
    try {
      const result = await SDKAuth.socialSignIn(provider);
      navigation.replace('HomeScreen');
    } catch (error) {
      Alert.alert('Social Login Failed', error.message);
    }
  };

  return (
    <View style={{ padding: 20 }}>
      <TextInput
        placeholder="Email"
        value={email}
        onChangeText={setEmail}
        style={{ marginBottom: 10, borderWidth: 1, padding: 10 }}
      />
      <TextInput
        placeholder="Password"
        value={password}
        onChangeText={setPassword}
        secureTextEntry
        style={{ marginBottom: 20, borderWidth: 1, padding: 10 }}
      />
      <Button title="Login" onPress={handleLogin} />
      <Button title="Login with Google" onPress={() => handleSocialLogin('google')} />
    </View>
  );
};
```

### Example 3: Real-time Data with WebSocket
```javascript
// hooks/useRealTimeData.js
import { useState, useEffect } from 'react';
import { SDKWebSocket } from '@pratik.vekariya1/react-native-sdk';

export const useRealTimeData = (channel) => {
  const [data, setData] = useState(null);
  const [connected, setConnected] = useState(false);

  useEffect(() => {
    const websocket = new SDKWebSocket({
      channel,
      onConnect: () => setConnected(true),
      onDisconnect: () => setConnected(false),
      onMessage: (message) => setData(message),
      onError: (error) => console.error('WebSocket error:', error),
    });

    websocket.connect();

    return () => websocket.disconnect();
  }, [channel]);

  return { data, connected };
};

// Usage in component
const LiveDataComponent = () => {
  const { data, connected } = useRealTimeData('live-updates');

  return (
    <View>
      <Text>Status: {connected ? 'Connected' : 'Disconnected'}</Text>
      {data && <Text>Latest: {JSON.stringify(data)}</Text>}
    </View>
  );
};
```

## 🔧 Advanced Configuration

### Custom Network Configuration
```javascript
import { configureNetwork } from '@pratik.vekariya1/react-native-sdk';

configureNetwork({
  baseURL: 'https://your-api.com',
  timeout: 15000,
  headers: {
    'Custom-Header': 'value',
    'App-Version': '1.0.0'
  },
  interceptors: {
    request: (config) => {
      // Modify request before sending
      config.headers.timestamp = Date.now();
      return config;
    },
    response: (response) => {
      // Process response data
      return response.data;
    },
    error: (error) => {
      // Handle network errors
      console.log('Network error:', error);
      return Promise.reject(error);
    }
  }
});
```

### Theme Customization
```javascript
import { configureTheme } from '@pratik.vekariya1/react-native-sdk';

configureTheme({
  colors: {
    primary: '#007AFF',
    secondary: '#34C759',
    background: '#FFFFFF',
    surface: '#F2F2F7',
    text: '#000000',
    error: '#FF3B30'
  },
  spacing: {
    xs: 4,
    sm: 8,
    md: 16,
    lg: 24,
    xl: 32
  },
  typography: {
    fontFamily: 'System',
    sizes: {
      small: 14,
      medium: 16,
      large: 20,
      xlarge: 24
    }
  }
});
```

### Performance Optimization
```javascript
import { optimizePerformance } from '@pratik.vekariya1/react-native-sdk';

optimizePerformance({
  enableCaching: true,
  cacheSize: 50, // MB
  enableCompression: true,
  batchRequests: true,
  requestBatchSize: 10,
  enableImageOptimization: true,
  preloadCriticalData: ['user-profile', 'app-config']
});
```

## 🔌 API Reference

### Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiKey` | `string` | `required` | Your API key for authentication |
| `environment` | `'development' \| 'production'` | `'production'` | Environment setting |
| `timeout` | `number` | `10000` | Request timeout in milliseconds |
| `retryAttempts` | `number` | `2` | Number of retry attempts |
| `debugMode` | `boolean` | `false` | Enable debug logging |

### Methods

#### `initializeSDK(config: SDKConfig)`
Initializes the SDK with the provided configuration.

**Parameters:**
- `config` - Configuration object

**Example:**
```javascript
initializeSDK({
  apiKey: 'your-api-key',
  environment: 'production'
});
```

#### `getSDKVersion(): string`
Returns the current SDK version.

#### `configure(options: ConfigOptions)`
Updates SDK configuration after initialization.

### Components

#### `SDKComponent`

**Props:**
| Prop | Type | Required | Description |
|------|------|----------|-------------|
| `onSuccess` | `(data: any) => void` | No | Success callback |
| `onError` | `(error: Error) => void` | No | Error callback |
| `style` | `ViewStyle` | No | Custom styling |

## 🛠️ Step-by-Step Integration Checklist

### ✅ Pre-Integration Checklist
- [ ] React Native version 0.65 or higher
- [ ] Node.js 14+ installed
- [ ] iOS 11+ / Android API 21+ target
- [ ] Valid API key from your service

### ✅ Installation Checklist
- [ ] Package installed via npm/yarn/pnpm
- [ ] iOS pods installed (`cd ios && pod install`)
- [ ] Android build.gradle updated with minSdkVersion 21
- [ ] Clean cache if needed (`npx react-native start --reset-cache`)

### ✅ Configuration Checklist
- [ ] SDK initialized in App.js or index.js
- [ ] API key configured
- [ ] Environment set (development/production)
- [ ] Debug mode enabled for development
- [ ] Network configuration completed

### ✅ Testing Checklist
- [ ] Basic SDK functionality works
- [ ] Error handling implemented
- [ ] Loading states handled
- [ ] Works on both iOS and Android
- [ ] Performance acceptable

## 🔄 Migration Guide

### From Version 0.x to 1.x
```javascript
// OLD (v0.x)
import SDK from '@pratik.vekariya1/react-native-sdk';
SDK.init('your-api-key');

// NEW (v1.x)
import { initializeSDK } from '@pratik.vekariya1/react-native-sdk';
initializeSDK({
  apiKey: 'your-api-key',
  environment: 'production'
});
```

### Breaking Changes in v1.x
1. **Initialization method changed** - Use `initializeSDK()` instead of `SDK.init()`
2. **Import structure updated** - Named imports instead of default
3. **Configuration object required** - API key alone is not sufficient

## 🐛 Common Integration Issues & Solutions

### Issue: "Module not found" Error
```bash
# Solution: Clear cache and reinstall
npm start -- --reset-cache
rm -rf node_modules
npm install
cd ios && pod install
```

### Issue: iOS Build Fails
```bash
# Solution: Clean iOS build
cd ios
xcodebuild clean
rm -rf build/
pod install
cd .. && npx react-native run-ios
```

### Issue: Android Build Fails
```bash
# Solution: Clean Android build
cd android
./gradlew clean
cd .. && npx react-native run-android
```

### Issue: SDK Not Initializing
```javascript
// Check if SDK is properly initialized
import { isSDKReady } from '@pratik.vekariya1/react-native-sdk';

const checkSDKStatus = () => {
  if (!isSDKReady()) {
    console.log('SDK not ready. Check your configuration.');
    return false;
  }
  return true;
};
```

### Issue: Network Requests Failing
```javascript
// Enable debug mode to see network logs
initializeSDK({
  apiKey: 'your-key',
  environment: 'development',
  debugMode: true, // This will show detailed logs
  networkLogging: true
});
```

## 📋 Integration Best Practices

### 1. Error Boundary Implementation
```javascript
import React from 'react';
import { Text, View } from 'react-native';

class SDKErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {
    console.log('SDK Error Boundary:', error, errorInfo);
    // Report to error tracking service
  }

  render() {
    if (this.state.hasError) {
      return (
        <View style={{ padding: 20, alignItems: 'center' }}>
          <Text>Something went wrong with SDK</Text>
        </View>
      );
    }

    return this.props.children;
  }
}

// Wrap your SDK components
<SDKErrorBoundary>
  <YourSDKComponent />
</SDKErrorBoundary>
```

### 2. Loading State Management
```javascript
import React, { useState, useEffect } from 'react';
import { View, ActivityIndicator } from 'react-native';
import { initializeSDK, isSDKReady } from '@pratik.vekariya1/react-native-sdk';

const App = () => {
  const [sdkReady, setSDKReady] = useState(false);

  useEffect(() => {
    const initSDK = async () => {
      try {
        await initializeSDK({
          apiKey: 'your-key',
          environment: 'production'
        });
        setSDKReady(isSDKReady());
      } catch (error) {
        console.error('SDK initialization failed:', error);
      }
    };

    initSDK();
  }, []);

  if (!sdkReady) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <ActivityIndicator size="large" />
      </View>
    );
  }

  return (
    // Your app content
  );
};
```

### 3. Secure API Key Storage
```javascript
// Never hardcode API keys in production
// Use react-native-config or similar
import Config from 'react-native-config';

initializeSDK({
  apiKey: Config.SDK_API_KEY, // Stored in .env file
  environment: Config.ENVIRONMENT
});
```

## 🔍 Troubleshooting

### Common Issues

#### Issue: Module not found
**Solution:** Make sure to run `pod install` for iOS and clean your build cache:
```bash
# For iOS
cd ios && pod install

# Clean cache
npx react-native start --reset-cache
```

#### Issue: Build errors on Android
**Solution:** Ensure your `android/build.gradle` has the minimum SDK version:
```gradle
minSdkVersion 21
```

### Debug Mode

Enable debug mode to get detailed logs:
```javascript
configure({ debugMode: true });
```

## 📊 Performance

- Bundle size: ~50KB (minified + gzipped)
- Memory footprint: < 5MB
- Startup time: < 100ms

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Setup

1. Clone the repository
2. Install dependencies: `npm install`
3. Run tests: `npm test`
4. Build: `npm run build`

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🔗 Links

- [Documentation](https://docs.example.com)
- [Examples](https://github.com/pratik-vekariya/react-native-sdk-examples)
- [Changelog](CHANGELOG.md)
- [Issues](https://github.com/pratik-vekariya/react-native-sdk/issues)

## 👨‍💻 Author

**Pratik Vekariya**
- GitHub: [@pratik-vekariya](https://github.com/pratik-vekariya)
- Email: pratik.vekariya@montra.org

## 🙏 Acknowledgments

- React Native community for the amazing framework
- Contributors who helped improve this SDK
- Open source libraries that made this possible

## 📈 Changelog

### [1.0.0] - 2025-01-15
- Initial release
- Basic SDK functionality
- Cross-platform support

---

Made with ❤️ by [Pratik Vekariya](https://github.com/pratik-vekariya)