Passio Nutrition-AI
  • Nutrition-AI SDK Overview
  • Guides
    • Nutrition AI SDK
      • SDK Key and minimum requirements
      • Installation
      • Configure the SDK
      • Use Cases
        • Food recognition
        • Nutrition data
        • Barcode scanning
        • Nutrition Facts scanning
        • Search, Food Icons, RefCode
        • Speech recognition
        • Nutrition Advisor
        • Suggestions and Meal Plans
        • User created foods and reports
    • iOS SDK Docs
      • Before getting started
      • Getting the ml models to the device
      • Run the demos first
      • Adding Passio SDK into your project
      • Initialize and configure the SDK
      • Start/Stop food detection
      • Food Recognition Delegate
      • Migration from SDK 1.4.X to 2.x
      • SDK API
      • Quick Start Guide
        • Installation
        • Configure the SDK (UIKit)
        • Recognise food using image
        • Food Details
    • Android SDK Docs
      • Getting started
        • Include the library
        • Camera
        • SDK Initialization and Configuration
        • Food detection session
        • Visual, Barcode and Packaged Food detection
        • Nutritional Database
        • Sandbox app
      • Troubleshooting on Android
      • Migration from SDK version 1.4.x to 2.x
      • Quick Start Guide
        • Importing the Android SDK to a project
        • Configure SDK and handle the result
        • RecognizeImageRemote
        • Food Details
    • React Native SDK Docs
      • Getting Started
        • Installation
        • SDK Initialization and Configuration
      • API Reference
        • configure & requestCameraAuthorization
        • recognizeImageRemote
        • searchForFood & searchForFoodSemantic
        • startFoodDetection
          • FoodDetectionEvent
        • fetchFoodItemForProductCode
        • fetchFoodItemForRefCode
        • fetchFoodItemForDataInfo
        • startNutritionFactsDetection
        • fetchFoodItemForPassioID
        • recognizeSpeechRemote
        • Fetch Nutrients
        • onDowloadingPassioModelCallBacks
        • detectFoodFromImageURI
        • addToPersonalization
        • updateLanguage
        • fetchHiddenIngredients
        • fetchVisualAlternatives
        • fetchPossibleIngredients
      • Properties
        • PassioFoodItem
        • PassioFoodDataInfo
        • PassioFoodAmount
        • PassioIngredient
        • PassioNutrients
        • UnitMass
        • ServingUnit
        • ServingSize
        • PassioSearchResult
        • NutritionFacts
        • PassioNutritionPreview
        • PassioSpeechRecognitionModel
        • PassioLogAction
        • PassioAdvisorFoodInfo
        • FoodCandidates
        • FoodDetectionEvent
        • NutritionDetectionEvent
        • DetectedCandidate
        • BarcodeCandidate
        • PackagedFoodCode
        • AmountEstimate
        • ImagesInfo
        • PassioStatus
        • FoodDetectionEvent
        • NutritionFacts
        • PassioMealPlan
        • PassioMealPlanItem
      • Nutriton Advisor
        • initConversation
        • sendMessage
        • sendImage
        • Guide
          • useNutritionAdvisor
        • Properties
          • PassioAdvisorResponse
          • PassioAdvisorMessageResultStatus
          • PassioAdvisorResultStatus
      • Quick Start Guide
        • Installation
        • Configure the SDK
        • RecognizeImageRemote
        • Food Detail
      • Guide
        • Integrate SDK Setup
        • Integrate Quick Scan
        • Integrate Food Search
        • Integrate Food Editor with Recipe
        • Integrate MealPlan
        • Integrate Suggestions
        • Integrate recognizeImageRemote
      • Components
        • DetectionCameraView
        • PassioIconView
      • Changelog
      • More
        • Display Macro Chart
          • MockFood
          • Utils PassioNutrient
        • Display Micro Progress
        • Getting nutrition value for a FoodItem
        • Getting nutrition value for a Recipe
        • Recalculate the nutrition value based on serving size options.
      • Migrations
        • Migrating from SDK 2.X to version 3.X
        • Structure Migrations From SDK 3.X to SDK 2.X
        • [Deprecated] Migrating from SDK 1.X to version 2.X
        • [Deprecated] Getting Started (v1)
          • Installation
          • SDK Initialization and Configuration
          • Start food detection
          • FoodDetectionEvent
          • Nutritional Database
      • Troubleshooting on RN
      • V2
        • Getting Started
          • Installation
          • SDK Initialization and Configuration
          • Start food detection
          • FoodDetectionEvent
        • RN SDK API
          • Properties
            • PersonalizedAlternative
            • FoodSearchResult
            • PassioNutrient
            • FoodDetectionEvent
            • DownloadModelCallBack
            • UPCProduct
            • ServingUnit
            • PassioStatus
            • PassioIDAttributes
            • PassioIDEntityType
            • PassioFoodItem
            • PassioRecipe
            • ServingSize
            • Measurement
            • UnitMass
            • NutritionFacts
        • Food Image
        • Search Food Item
        • Quick Scan
        • Multi Scan
        • MealPlan
        • Recipe
      • How do I Integrate a Passio SDK in EXPO?
    • Flutter SDK Docs
      • Getting Started
    • Before You Continue
    • Setup For Android
    • Initialize and configure the SDK
  • Fundamentals
    • Nutrition-AI Developer FAQ
      • Nutrition Data
      • Supported Phones
      • Security
      • Testing Volume Estimation
      • Testing Nutrition-AI SDK
      • Nutrition-AI Test Methodology
    • Nutrition API - Mobile SDK interoperability
      • JSON Response parsing
  • Versions
    • 3.2.4
      • SDK Key and minimum requirements
      • Installation
      • Configure the SDK
      • Use Cases
        • Food recognition
        • Nutrition data
        • Barcode scanning
        • Nutrition Facts scanning
        • Search, Food Icons, RefCode
        • Speech recognition
        • Nutrition Advisor
        • Suggestions and Meal Plans
        • User created foods and reports
    • 3.2.2
      • SDK Key and minimum requirements
      • Installation
      • Configure the SDK
      • Use Cases
        • Food recognition
        • Nutrition data
        • Barcode scanning
        • Nutrition Facts scanning
        • Search, Food Icons, RefCode
        • Speech recognition
        • Nutrition Advisor
        • Suggestions and Meal Plans
        • User created foods and reports
    • 3.2.0
      • SDK Key and minimum requirements
      • Installation
      • Configure the SDK
      • Use Cases
        • Food recognition
        • Nutrition data
        • Barcode scanning
        • Nutrition Facts scanning
        • Search, Food Icons, RefCode
        • Speech recognition
        • Nutrition Advisor
        • Suggestions and Meal Plans
    • 3.1.4
      • SDK Key and minimum requirements
      • Installation
      • Configure the SDK
      • Use Cases
        • Food recognition
        • Nutrition data
        • Barcode scanning
        • Search, Food Icons, RefCode
        • Speech recognition
        • Nutrition Advisor
        • Suggestions and Meal Plans
Powered by GitBook
On this page
  • Example
  • MicrosView
  • useMicroNutrients
  • Result
Export as PDF
  1. Guides
  2. React Native SDK Docs
  3. More

Display Micro Progress

Display Micro nutrients progress using nutrients from PassioFoodItem and PassioRecipe.

PreviousUtils PassioNutrientNextGetting nutrition value for a FoodItem

Last updated 1 year ago

Example

Obtain the utility function for fetching nutrition from the provided page.

MicrosView

import React from 'react';
import { View } from 'react-native';
import { FlatList } from 'react-native';
import { unitForNutrient } from '../../../models';
import { microItemStyle } from './microView.styles';
import { useMicroNutrients, type MicroNutrition } from './useMicroNutrients';
import { Text } from 'react-native';

const MicrosView = () => {
  // Fetch micro-nutrition data using the custom hook
  const { microNutrition } = useMicroNutrients();

  // Render function for each micro-nutrient item
  const renderMicroItem = (micro: MicroNutrition) => {
    const { title, recommended, achieved } = micro;
    const unit = unitForNutrient(micro.id);

    // Set userAchieved to 0 if achieved is null or undefined
    const userAchieved =
      achieved !== null && achieved !== undefined ? achieved : 0;

    // Calculate remaining micro-nutrient value
    const remain = Math.max(0, recommended - userAchieved);

    return (
      <View>
        <View style={microItemStyle.infoContainer}>
          <Text style={microItemStyle.title}>
            {`${title} `}
            <Text
              style={microItemStyle.achieved}
            >{`${userAchieved.toFixed(2)} ${unit}`}</Text>
          </Text>
          <View style={microItemStyle.recommendedContainer}>
            <Text style={microItemStyle.recommendedValue}>
              {`${Math.round(remain).toFixed(2)} ${unit}`}
            </Text>
            <Text style={microItemStyle.remainingText}>{'Remaining'}</Text>
          </View>
        </View>
        <View style={microItemStyle.progressContainer}>
          <View
            style={[
              { flex: Math.round(userAchieved) },
              microItemStyle.progress,
            ]}
          />
          <View style={{ flex: Math.round(remain) }} />
        </View>
      </View>
    );
  };

  return (
    <FlatList
      data={microNutrition}
      contentContainerStyle={microItemStyle.list}
      renderItem={({ item }: { item: MicroNutrition }) => renderMicroItem(item)}
      keyExtractor={(__: MicroNutrition, index: number) => index.toString()}
      extraData={microNutrition}
    />
  );
};

// Wrap the MicrosView component with the withLoading higher-order component
export default MicrosView;

export const microItemStyle = StyleSheet.create({
  infoContainer: {
    flexDirection: 'row',
    paddingVertical: 8,
    alignItems: 'center',
  },
  title: {
    color: COLORS.grey7,
    paddingStart: 16,
    fontSize: 15,
    flex: 1,
    fontWeight: '600',
    alignItems: 'center',
  },
  achieved: {
    color: "gray",
    paddingHorizontal: 8,
    fontSize: 15,
    fontWeight: '400',
    alignItems: 'center',
  },
  remainingText: {
    color: "gray",
    fontWeight: '400',
    paddingHorizontal: 8,
    alignItems: 'center',
  },
  recommendedContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  recommendedValue: {
    minWidth: 70,
    color: "gray",
    alignSelf: 'center',
    alignItems: 'center',
    textAlign: 'center',
    fontWeight: '600',
    borderRadius: 28,
    padding: 4,
  },
  progressContainer: {
    flex: 1,
    backgroundColor: "gray",
    height: 10,
    flexDirection: 'row',
    marginHorizontal: 16,
    borderRadius: 16,
  },
  progress: {
    backgroundColor: "blue",
    borderRadius: 16,
  },
  list: {
    paddingBottom: 50,
  },
});

useMicroNutrients

import { useEffect, useState } from 'react';
import {
  getNutrientsFromAttribute,
  mergeNutrients,
  micros,
  type Nutrients,
  type NutrientsTypes,
} from '../../../utils/PassioNutrient';
import { mockFood } from '../macro/mockFood';
import { PassioSDK } from '@passiolife/nutritionai-react-native-sdk-v2';

export interface MicroNutrition {
  recommended: number;
  title: string;
  id: NutrientsTypes;
  achieved?: number;
}

export const useMicroNutrients = () => {
  // State to store micro-nutrition data
  const [microNutrition, setMicroNutrition] = useState<MicroNutrition[]>([]);

  // Food logs from mock data
  const foodLogs = mockFood;

  useEffect(() => {
    // Function to initialize and fetch micro-nutrition data
    async function init() {
      // Array to store micro-nutrient data
      let data: Nutrients[] = [];

      // Iterate through food logs to fetch attributes and extract micro-nutrients
      await Promise.all(
        foodLogs.map(async (item) => {
          const attribute = await PassioSDK.getAttributesForPassioID(
            item.passioID
          );

          // If attributes are available, extract micro-nutrients
          if (attribute) {
            const nutrients = getNutrientsFromAttribute(attribute, micros);
            data.push(...nutrients);
          }
        })
      );

      // Merge the micro-nutrient data
      data = mergeNutrients(data);

      // Define default micro-nutrients with recommended values
      const defaultMicroNutrients: MicroNutrition[] = [
        {
          title: 'dietaryFiber',
          id: 'fiber' as const,
          recommended: 28,
        },
        {
          title: 'sugar',
          id: 'sugar' as const,
          recommended: 50,
        },
        {
          id: 'saturatedFat' as const,
          title: 'SaturatedFat',
          recommended: 20,
        },
        {
          id: 'transFat' as const,
          title: 'transFat',
          recommended: 0,
        },
        {
          id: 'polyunsaturatedFat' as const,
          title: 'polyunsaturatedFat',
          recommended: 22,
        },
        {
          id: 'monounsaturatedFat' as const,
          title: 'monounsaturatedFat',
          recommended: 44,
        },
        {
          id: 'cholesterol' as const,
          title: 'cholesterol',
          recommended: 300,
        },
        {
          title: 'sodium',
          id: 'sodium' as const,
          recommended: 2300,
        },
        {
          id: 'potassium' as const,
          title: 'potassium',
          recommended: 4700,
        },
        {
          id: 'iron' as const,
          title: 'iron',
          recommended: 18,
        },
        {
          id: 'magnesium' as const,
          title: 'magnesium',
          recommended: 420,
        },
        {
          id: 'iodine' as const,
          title: 'iodine',
          recommended: 150,
        },
        {
          id: 'vitaminA' as const,
          title: 'vitaminA',
          recommended: 900,
        },
        {
          id: 'vitaminB6' as const,
          title: 'vitaminB6',
          recommended: 1.7,
        },
        {
          id: 'vitaminB12' as const,
          title: 'vitaminB12',
          recommended: 2.4,
        },
        {
          id: 'vitaminC' as const,
          title: 'vitaminC',
          recommended: 90,
        },
        {
          id: 'vitaminD' as const,
          title: 'vitaminD',
          recommended: 20,
        },
        {
          id: 'vitaminE' as const,
          title: 'vitaminE',
          recommended: 15,
        },
      ].map((item) => ({
        ...item,
        // Calculate achieved value by filtering the micro-nutrient data
        achieved: data.find(
          (allNutrimentItem) => allNutrimentItem.name === item.id
        )?.unitMass?.value,
      }));

      // Update the state with the processed micro-nutrient data
      setMicroNutrition(defaultMicroNutrients);
    }

    // Call the init function
    init();
  }, [foodLogs]); // Re-run the effect when foodLogs change

  // Return the micro-nutrition data
  return {
    microNutrition,
  };
};

Result

Utils PassioNutrient