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
  • Display a Macronutrient chart using nutrients from PassioFoodItem and PassioRecipe.
  • Example
  • MacrosNutrient
  • useMacrosNutrients
  • Result
Export as PDF
  1. Guides
  2. React Native SDK Docs
  3. More

Display Macro Chart

PreviousMoreNextMockFood

Last updated 1 year ago

Display a Macronutrient chart using nutrients from PassioFoodItem and PassioRecipe.

Require victory-native and react-native-svg npm package to display the chart.

yarn install victory-native

yarn install react-native-svg

Example

Displaying the nutritional values for calories, carbs, proteins, and fats using the mockFood data, which includes logged dates for the respective food entries.

Retrieve mock data from this.

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

MacrosNutrient

import React from 'react';
import { Text, View, ScrollView } from 'react-native';
import {
  VictoryAxis,
  VictoryBar,
  VictoryChart,
  VictoryLabel,
  VictoryTheme,
} from 'victory-native';
import { useMacrosNutrients } from './useMacrosNutrients';
import {
  mergeAndSumMacroChartData,
  type NutrientsTypes,
} from '../../../utils/PassioNutrient';

// Color mapping for each nutrient type
const NutrientColors = {
  calories: '#FF4D61',
  fat: '#00D795',
  protein: '#0899FF',
  carbs: '#00D795',
};

const MacrosNutrient = () => {
  // Fetch nutrient data using custom hook
  const { passioIDAttributesData, macros } = useMacrosNutrients();

  // Function to render individual nutrient chart
  const renderNutrientChart = (item: NutrientsTypes) => (
    <View key={item}>
      {/* Nutrient type label */}
      <Text style={{ marginVertical: 8, alignSelf: 'center' }}>{item}</Text>

      {/* Victory Chart for the nutrient */}
      <VictoryChart theme={VictoryTheme.material} height={200}>
        {/* X-axis configuration */}
        <VictoryAxis
          style={{
            ticks: { stroke: 'transparent' },
            grid: { stroke: 'none' },
            axis: { stroke: '#F7F7F7' },
            tickLabels: { fill: '#333333', fontSize: 14 },
            axisLabel: {},
          }}
        />

        {/* Y-axis configuration */}
        <VictoryAxis
          dependentAxis
          fixLabelOverlap
          style={{
            ticks: { stroke: 'transparent' },
            axis: { stroke: 'none' },
            grid: { stroke: '#F7F7F7' },
            axisLabel: { padding: 0 },
            tickLabels: { fill: '#333333', fontSize: 14 },
          }}
        />

        {/* Victory Bar chart for the nutrient */}
        <VictoryBar
          cornerRadius={8}
          labelComponent={
            <VictoryLabel
              text={({ datum }) => Math.round(datum.value)}
              dy={-10}
            />
          }
          alignment="middle"
          style={{
            data: {
              borderTop: 24,
              width: 20,
              fill: NutrientColors[item],
            },
          }}
          data={mergeAndSumMacroChartData(
            passioIDAttributesData.filter((data) => data.type === item)
          )}
          x={(d) => d.label}
          y="value"
        />
      </VictoryChart>
    </View>
  );

  // Render the component
  return (
    <ScrollView>
      <View>
        {/* Iterate over nutrient types and render charts */}
        {macros.map(renderNutrientChart)}
      </View>
    </ScrollView>
  );
};

export default MacrosNutrient;

useMacrosNutrients

import { useEffect, useMemo, useState } from 'react';
import {
  getNutrientsFromAttribute,
  type NutrientsTypes,
} from '../../../utils/PassioNutrient';
import { PassioSDK } from '@passiolife/nutritionai-react-native-sdk-v2';
import { DateTime } from 'luxon';
import { mockFood } from './mockFood';

export interface MacroChartData {
  label: string;
  value: number;
  type: NutrientsTypes;
}

export const useMacrosNutrients = () => {
  // State to store nutrient data

  const macros: NutrientsTypes[] = useMemo(() => {
    return ['calories', 'carbs', 'fat', 'protein'];
  }, []);

  const [passioIDAttributesData, setPassioIDAttributesData] = useState<
    MacroChartData[]
  >([]);

  // Effect to fetch and process nutrient data on component mount
  useEffect(() => {
    // Temporary array to store processed nutrient data
    const data: MacroChartData[] = [];

    async function fetchData() {
      // Create a copy of mockFood array to avoid modifying the original
      const copyFood = [...mockFood];

      // Fetch attributes for each PassioID and process nutrient data
      await Promise.all(
        copyFood.map(async (foodLog) => {
          // Get attributes for a PassioID using PassioSDK
          const attribute = await PassioSDK.getAttributesForPassioID(
            foodLog.passioID
          );

          // If attributes are available, process the nutrients
          if (attribute) {
            // Get nutrients from the attribute for specific nutrient types
            getNutrientsFromAttribute(attribute, macros).forEach((item) => {
              // Convert timestamp to a formatted date and add the nutrient data to the array
              data.push({
                label: DateTime.fromJSDate(
                  new Date(foodLog.eventTimestamp)
                ).toFormat('dd/MM'),
                value: item.unitMass?.value ?? 0,
                type: item.name,
              });
            });
          }
        })
      );

      // Update the state with the processed nutrient data
      setPassioIDAttributesData(data);
    }

    // Call the fetchData function
    fetchData();
  }, [macros]); // Empty dependency array to ensure the effect runs only once on mount

  // Return the macros constant and the processed nutrient data
  return {
    macros,
    passioIDAttributesData,
  };
};

Result

MockFood
Utils PassioNutrient