Getting nutrition value for a Recipe

In this we get nutritional value form PassioID and PassioRecipe ?

/* You can utilize the getNutrientsFromRecipe method, 
  declaring it as shown below, to retrieve specific
  macro or micronutrient information from a recipe.
*/
  
  useEffect(() => {
    // Fetch Passio Food Item details when component mounts
    const init = async () => {
      const result = await PassioSDK.getAttributesForPassioID(passioID);
      if (result && result.recipe && result) {
        const macroNutrients = getNutrientsFromRecipe(result.recipe, macros);
       const  microsNutrients = getNutrientsFromRecipe(result.recipe, micros);
     
      }
    };

    init();
  }, [passioID]);


 const micros: NutrientsTypes[] = [
  'saturatedFat',
  'transFat',
  'polyunsaturatedFat',
  'sodium',
  'fiber',
  'sugar',
  'sugarAdded',
  'vitaminD',
  'iron',
  'potassium',
  'vitaminA',
  'alcohol',
  'sugarAlcohol',
  'vitaminB12',
  'vitaminB12Added',
  'vitaminB6',
  'vitaminE',
  'vitaminEAdded',
  'phosphorus',
  'iodine',
  'cholesterol',
];

 const macros: NutrientsTypes[] = ['calories', 'carbs', 'protein', 'fat'];

Methods

getNutrientsFromRecipe


export const getNutrientsFromRecipe = (
  recipe: PassioRecipe,
  type: NutrientsTypes[]
): Nutrients[] => {
  let nutrients: Nutrients[] = [];
  recipe.foodItems.forEach((item) => {
    nutrients.push(...getNutrients(item, type));
  });
  return mergeNutrients(nutrients);
};

getNutrients


// Get multiple nutrients from Passio FoodItem
const getNutrients = (
  foodItem: PassioFoodItem,
  nutrientNames: NutrientsTypes[]
): Nutrients[] => {
  return nutrientNames
    .map((name) => {
      // Handle special case for 'vitaminA'
      if (name === 'vitaminA') {
        return {
          name,
          unitMass: {
            value: foodItem.vitaminA ?? 0,
            unit: '',
          },
        };
      }
      // General case for other nutrients
      return getNutrient(foodItem, name);
    })
    .filter((item): item is Nutrients => !!item);
};

getNutrientFromRecipe

export const getNutrientFromRecipe = (
  recipe: PassioRecipe,
  type: NutrientsTypes
): Nutrients[] => {
  let nutrients: Nutrients[] = [];
  recipe.foodItems.forEach((item) => {
    const result = getNutrient(item, type);
    if (result) {
      nutrients.push(result);
    }
  });
  return mergeNutrients(nutrients);
};

getNutrient


// Get a single nutrient from Passio Food Item
const getNutrient = (
  foodItem: PassioFoodItem,
  name: NutrientsTypes
): Nutrients | null => {
  if (foodItem[name]) {
    return {
      name,
      unitMass: foodItem[name] ?? undefined,
    } as Nutrients;
  } else {
    return null;
  }
};

Example

MacroInfoRecipe View

import React, { useState, useEffect } from 'react';
import { StyleSheet, View } from 'react-native';
import {
  PassioSDK,
  type PassioID,
} from '@passiolife/nutritionai-react-native-sdk-v2';
import { Text } from 'react-native';
import { FlatList } from 'react-native';
import {
  formatNutrient,
  getNutrientsFromRecipe,
  macros,
  micros,
  type Nutrients,
} from './MacroUtils';

export const MacroInfoRecipe = ({ passioID }: { passioID: PassioID }) => {
  const [macroNutrients, setMacroNutrients] = useState<Nutrients[]>();
  const [microNutrients, setMicroNutrients] = useState<Nutrients[]>();

  useEffect(() => {
    // Fetch Passio Food Item details when component mounts
    const init = async () => {
      const result = await PassioSDK.getAttributesForPassioID(passioID);
      if (result && result.recipe && result) {
        setMacroNutrients(getNutrientsFromRecipe(result.recipe, macros));
        setMicroNutrients(getNutrientsFromRecipe(result.recipe, micros));
      }
    };

    init();
  }, [passioID]);

  // Function to render individual nutrient information
  const renderInformation = ({ item }: { item: Nutrients }) => {
    const { name, unitMass } = item;
    return (
      <View style={styles.infoRow}>
        <Text style={[styles.infoText, styles.infoTitle]}>{name}</Text>
        <Text style={[styles.infoText, styles.infoValue]}>
          {formatNutrient(unitMass?.value ?? 0)}
        </Text>
      </View>
    );
  };

  return (
    <View style={styles.container}>
      {/* Display Macro Nutrients */}
      <Text style={styles.heading}>Macro Nutrients</Text>
      {macroNutrients && (
        <FlatList data={macroNutrients} renderItem={renderInformation} />
      )}

      {/* Display Micro Nutrients */}
      <Text style={styles.heading}>Micro Nutrients</Text>
      {microNutrients && (
        <FlatList data={microNutrients} renderItem={renderInformation} />
      )}
    </View>
  );
};
// Styles for the component
export const styles = StyleSheet.create({
  container: { flex: 1, paddingHorizontal: 16 },
  heading: { fontSize: 18, fontWeight: '600', marginVertical: 16 },
  infoRow: { flexDirection: 'row', marginVertical: 4 },
  infoText: { fontSize: 16 },
  infoTitle: { flex: 1 },
  infoValue: {},
});

Utility Methods


export const micros: NutrientsTypes[] = [
  'saturatedFat',
  'transFat',
  'polyunsaturatedFat',
  'sodium',
  'fiber',
  'sugar',
  'sugarAdded',
  'vitaminD',
  'iron',
  'potassium',
  'vitaminA',
  'alcohol',
  'sugarAlcohol',
  'vitaminB12',
  'vitaminB12Added',
  'vitaminB6',
  'vitaminE',
  'vitaminEAdded',
  'phosphorus',
  'iodine',
  'cholesterol',
];

export const macros: NutrientsTypes[] = ['calories', 'carbs', 'protein', 'fat'];

export const formatNutrient = (value?: number): number => {
  try {
    return Number((value ? value : 0).toFixed(2));
  } catch (e) {
    return -1;
  }
};

mergeNutrients


export const mergeNutrients = (nutrientsArray: Nutrients[]): Nutrients[] => {
  const mergedMap = new Map<NutrientsTypes, Nutrients>();

  for (const nutrient of nutrientsArray) {
    const { name, unitMass } = nutrient;

    if (mergedMap.has(name)) {
      // Nutrient with the same name already exists, add their values
      const existingNutrient = mergedMap.get(name);
      if (existingNutrient && unitMass?.value !== undefined) {
        existingNutrient.unitMass = {
          value:
            (existingNutrient.unitMass?.value ?? 0) + (unitMass.value ?? 0),
          unit: unitMass.unit ?? '',
        };
      }
    } else {
      // Nutrient with this name doesn't exist yet, add it to the map
      mergedMap.set(name, {
        ...nutrient,
        unitMass: unitMass ? { ...unitMass } : undefined,
      });
    }
  }

  // Convert the map back to an array
  const mergedArray = Array.from(mergedMap.values());

  return mergedArray;
};

Result

Last updated