Skip to content

Commit

Permalink
implemented food/nutritable editing
Browse files Browse the repository at this point in the history
  • Loading branch information
ebbmango committed Jan 5, 2025
1 parent deb8200 commit e61ce61
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 14 deletions.
2 changes: 1 addition & 1 deletion components/FoodsListItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default function FoodListItem({ food, meal }: FoodListItemProps) {
<TouchableOpacity
style={[styles.listItem]}
onPress={() => {
navigation.navigate('Read', { food, meal });
navigation.navigate('Read', { foodId: food.id, meal });
}}>
<Text style={{ fontSize: 18 }}>{food.name}</Text>
<IconSVG name="arrow-right-solid" width={16} color={Colors.violet50} />
Expand Down
6 changes: 6 additions & 0 deletions database/queries/foodsQueries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ export const getAllFoods = async (database: SQLiteDatabase): Promise<Food[]> =>
}));
};

export const getFoodById = async (database: SQLiteDatabase, params: { foodId: number }): Promise<Food | null> => {
const query = "SELECT * FROM foods WHERE id = $foodId;";
const queryResult = await database.getFirstAsync<Food>(query, toSQLiteParams(params));
return queryResult;
};

export const getAllFoodNames = async (database: SQLiteDatabase): Promise<string[]> => {
const query = "SELECT name FROM foods;";
const queryResult = await database.getAllAsync(query);
Expand Down
2 changes: 1 addition & 1 deletion navigation/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export type RootStackParamList = {
List: { meal: Meal }; // Lists existing foods.
Create: undefined; // Creates food.

Read: { meal: Meal; food: Food }; // Displays food and its nutritables, allows:
Read: { meal: Meal; foodId: number }; // Displays food and its nutritables, allows:
// - Editing the food's name;
// - Adding a specified amount of said food to a previously selected meal.

Expand Down
35 changes: 26 additions & 9 deletions screens/Read.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ import MacrosAccordion from 'components/Screens/Read/MacrosAccordion';
import { StackNavigationProp } from '@react-navigation/stack';
import { RootStackParamList } from 'navigation';
import proportion from 'utils/proportion';
import { getFoodById } from 'database/queries/foodsQueries';

type Props = StaticScreenProps<{
food: Food;
foodId: number;
meal: Meal;
}>;

Expand All @@ -38,27 +39,38 @@ type UnitsQueryReturn = {
};

export default function Read({ route }: Props) {
const { food, meal } = route.params;
const { foodId, meal } = route.params;

const colors = useColors();
const screenWidth = Dimensions.get('window').width;
const navigation = useNavigation<StackNavigationProp<RootStackParamList>>();
const database: SQLiteDatabase = useSQLiteContext();

const {
data: food,
isFetched: foodFetched,
refetch: refetchFood,
} = useQuery({
queryKey: [`FoodNo.${foodId}`],
queryFn: () => getFoodById(database, { foodId }),
initialData: null,
});

// FETCHING the food's nutritables
const {
data: nutritables = [],
isFetched: nutritablesFetched,
refetch: refetchNutritables,
} = useQuery({
queryKey: [`FoodNo.${food.id}Nutritables`],
queryFn: () => getNutritablesByFood(database, { foodId: food.id }),
queryKey: [`FoodNo.${foodId}Nutritables`],
queryFn: () => getNutritablesByFood(database, { foodId }),
initialData: [],
});

// REFETCHES the food's nutritables on database change
addDatabaseChangeListener((change) => {
if (change.tableName === 'nutritables') refetchNutritables();
if (change.tableName === 'foods') refetchFood();
});

// FETCHING all possible measurement units
Expand Down Expand Up @@ -144,14 +156,16 @@ export default function Read({ route }: Props) {
setMacros(calculatedMacros);
}, [calculatedMacros]);

console.log(food);

// Return a blank screen if the relevant data has not as of yet been properly fetched.
if (
!food ||
!nutritablesFetched ||
!unitsFetched ||
!usedUnits ||
usedUnits.length === 0 ||
!unusedUnits ||
unusedUnits.length === 0
!unusedUnits
) {
return <></>;
}
Expand Down Expand Up @@ -179,7 +193,7 @@ export default function Read({ route }: Props) {
<MacroInputField
text={measurement}
onChangeText={(text) => setMeasurement(text)}
unitSymbol={nutritables[0].unit.symbol}
unitSymbol={selectedNutritable?.unit.symbol || '- - -'}
unitIndicatorWidth={60}
iconName={'scale-unbalanced-solid'}
maxLength={7}
Expand Down Expand Up @@ -263,12 +277,15 @@ export default function Read({ route }: Props) {
</Pressable>
{/* button: ADD nutritable */}
<Pressable
style={styles.button}
style={[
styles.button,
unusedUnits.length === 0 && { backgroundColor: Colors.violet60 },
]}
disabled={unusedUnits.length === 0}
onPress={() => navigation.navigate('Add', { food, units: unusedUnits })}>
<IconSVG
name="solid-square-list-circle-plus"
color={'white'}
color={unusedUnits.length === 0 ? Colors.violet80 : 'white'}
width={28}
style={{ marginLeft: 4 }}
/>
Expand Down
29 changes: 26 additions & 3 deletions screens/Update.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@ import MacrosBarChart from 'components/Screens/Create/MacrosBarChart';
import MacroInputField from 'components/Screens/Create/MacroInputField';

import { Food, Nutritable, Unit } from 'database/types';
import { getAllFoodNames } from 'database/queries/foodsQueries';
import { getAllFoodNames, updateFoodName } from 'database/queries/foodsQueries';

import calculateCalories from 'utils/calculateCalories';
import { validateFoodInputs } from 'utils/validation/validateFood';
import { Validation, ValidationStatus } from 'utils/validation/types';
import { StaticScreenProps } from '@react-navigation/native';
import { StaticScreenProps, useNavigation } from '@react-navigation/native';
import { updateNutritable } from 'database/queries/nutritablesQueries';
import { StackNavigationProp } from '@react-navigation/stack';
import { RootStackParamList } from 'navigation';

type Props = StaticScreenProps<{
food: Food;
Expand All @@ -35,6 +38,7 @@ export default function Update({ route }: Props) {

const colors = useColors();
const database: SQLiteDatabase = useSQLiteContext();
const navigation = useNavigation<StackNavigationProp<RootStackParamList>>();

// Fetches the names of all existing foods
const { data: names = [], isFetched: namesFetched } = useQuery({
Expand Down Expand Up @@ -199,7 +203,26 @@ export default function Update({ route }: Props) {
(tempValidationStatus.status === ValidationStatus.Warning && validationAttempted)
) {
// Creates the nutritable and redirects to the foods list
console.log('nutritable/food updated!');
if (food.name !== name) {
updateFoodName(database, { foodId: food.id, newFoodName: name });
}
if (
kcals !== nutritable.kcals.toString() ||
measure !== nutritable.baseMeasure.toString() ||
fat !== nutritable.fats.toString() ||
carbs !== nutritable.carbs.toString() ||
protein !== nutritable.protein.toString()
) {
updateNutritable(database, {
nutritableId: nutritable.id,
baseMeasure: Number(measure),
kcals: kcals.length === 0 ? Number(expectedKcals) : Number(kcals),
protein: Number(protein),
fats: Number(fat),
carbs: Number(carbs),
});
}
navigation.pop();
} else {
// Makes this validation result available to the rest of the program.
setValidation(tempValidationStatus);
Expand Down

0 comments on commit e61ce61

Please sign in to comment.