Skip to content

Commit

Permalink
fix display of unit in mealDrawer
Browse files Browse the repository at this point in the history
  • Loading branch information
ebbmango committed Jan 10, 2025
1 parent b62de40 commit 91b793a
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 16 deletions.
25 changes: 14 additions & 11 deletions components/Screens/Home/MealDrawer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { getNutritablesByIds } from 'database/queries/nutritablesQueries';
import { getFoodsByIds } from 'database/queries/foodsQueries';
import proportion from 'utils/proportion';
import { getAllUnits } from 'database/queries/unitsQueries';
import { useUnits } from 'database/hooks/useUnits';

type MealDrawerProps = {
meal: Meal;
Expand Down Expand Up @@ -97,12 +98,7 @@ export default function MealDrawer({ meal, summaries }: MealDrawerProps) {
enabled: entriesFetched && entries.length > 0,
});

// FETCHING all UNITS
const { data: units = [], isFetched: unitsFetched } = useQuery({
queryKey: ['allUnits'],
queryFn: () => getAllUnits(database),
initialData: [],
});
const { units, unitsFetched } = useUnits(database);

useEffect(() => {
const listener = addDatabaseChangeListener((change) => {
Expand All @@ -125,11 +121,12 @@ export default function MealDrawer({ meal, summaries }: MealDrawerProps) {
}, [entries]);

const entriesSummary: EntrySummary[] = useMemo(() => {
if (!foodsFetched || !nutritablesFetched) {
if (!foodsFetched || !nutritablesFetched || !unitsFetched) {
return [];
}

return entries.map((entry) => {
console.log(entry);
const nutritable = nutritables.find((table) => table.id === entry.nutritableId);
const food = foods.find((f) => f.id === entry.foodId);

Expand All @@ -141,21 +138,24 @@ export default function MealDrawer({ meal, summaries }: MealDrawerProps) {
food,
nutritableId: entry.nutritableId,
kcals: 0,
unit: '',
unitId: entry.unitId,
};
}

// console.log(units);
// console.log(nutritable);

return {
id: entry.id,
amount: entry.amount,
food,
nutritableId: entry.nutritableId,
kcals: proportion(nutritable.kcals, entry.amount, nutritable.baseMeasure),
// use optional chaining on unitId:
unit: units.find((u) => u.id === nutritable.unitId)?.symbol ?? '',
unitId: entry.unitId,
};
});
}, [entries, nutritables, foods, foodsFetched, nutritablesFetched, units]);
}, [entries, nutritables, foods, foodsFetched, nutritablesFetched, units, unitsFetched]);

return (
<ExpandableSection
Expand Down Expand Up @@ -202,6 +202,8 @@ function DrawerBody({ meal, entries }: DrawerBodyProps) {
const navigation = useNavigation<NavigationProp<RootStackParamList>>();
const screenWidth = Dimensions.get('window').width;

const { units } = useUnits(database);

return (
<View style={styles.sectionBody}>
{/* Each entry COMES HERE*/}
Expand Down Expand Up @@ -252,7 +254,8 @@ function DrawerBody({ meal, entries }: DrawerBodyProps) {
}}>
{/* <Text violet40>{`${entry.kcals} kcal `}</Text> */}
<Text style={{ flex: 1, fontSize: 16 }}>{entry.food.name}</Text>
<Text violet50>{`${entry.amount}${entry.unit}`}</Text>
<Text
violet50>{`${entry.amount}${units.find((u) => u.id === entry.unitId)?.symbol}`}</Text>
</View>
<View
row
Expand Down
Empty file.
8 changes: 5 additions & 3 deletions database/queries/foodsQueries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Food } from "database/types";
import toSQLiteParams from "utils/toSQLiteParams";

export const getAllFoods = async (database: SQLiteDatabase): Promise<Food[]> => {
const query = "SELECT * FROM foods;";
const query = "SELECT * FROM foods WHERE isDeleted = 0;";
const queryResult = await database.getAllAsync(query);
return queryResult.map((row: any) => ({
id: row.id,
Expand Down Expand Up @@ -34,7 +34,7 @@ export const getFoodsByIds = async (database: SQLiteDatabase, params: { ids: num
}

export const getAllFoodNames = async (database: SQLiteDatabase): Promise<string[]> => {
const query = "SELECT name FROM foods;";
const query = "SELECT name FROM foods WHERE isDeleted = 0;";
const queryResult = await database.getAllAsync(query);
return queryResult.map((row: any) => row.name)
}
Expand All @@ -45,8 +45,10 @@ export const createFood = (database: SQLiteDatabase, params: { foodName: string
};

export const deleteFood = (database: SQLiteDatabase, params: { foodId: number }) => {
const entry = database.getFirstSync("SELECT * FROM entries WHERE foodId = $foodId", toSQLiteParams(params))
const query = `DELETE FROM foods WHERE id = $foodId;`
return database.runSync(query, toSQLiteParams(params));
const altQuery = `UPDATE foods SET isDeleted = 1 WHERE id = $foodId;`
return database.runSync(entry ? query : altQuery, toSQLiteParams(params));
};

export const updateFoodName = (database: SQLiteDatabase, params: { foodId: number, newFoodName: string }) => {
Expand Down
23 changes: 21 additions & 2 deletions database/queries/nutritablesQueries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,10 @@ export const updateNutritable = (database: SQLiteDatabase, params: {
export const deleteNutritable = (database: SQLiteDatabase, params: {
nutritableId: number
}) => {
const entry = database.getAllSync("SELECT * FROM entries WHERE nutritableId = $nutritableId", toSQLiteParams(params))
const query = `DELETE FROM nutritables WHERE id = $nutritableId;`
return database.runSync(query, toSQLiteParams(params))
const altQuery = `UPDATE nutritables SET isDeleted = 1 WHERE id = $nutritableId;`
return database.runSync(entry ? query : altQuery, toSQLiteParams(params))
}

export const getNutritableById = async (database: SQLiteDatabase, params: { id: number }): Promise<Nutritable | null> => {
Expand All @@ -106,5 +108,22 @@ export const getNutritablesByIds = async (database: SQLiteDatabase, params: { id
paramDict[`id${index}`] = id;
});

return await database.getAllAsync<Nutritable>(query, toSQLiteParams(paramDict))
const queryReturn = await database.getAllAsync<Nutritable>(query, toSQLiteParams(paramDict))

return queryReturn.map((table: any) => ({
// identifiers
id: table.id,
foodId: table.foodId,
unit: {
id: table.unitId,
symbol: table.unitSymbol,
},
// measurements
baseMeasure: table.baseMeasure,
kcals: table.kcals,
carbs: table.carbs,
fats: table.fats,
protein: table.protein,
isDeleted: table.isDeleted
}));
}
2 changes: 2 additions & 0 deletions screens/Read.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import SegmentedMacrosBarChart from 'components/Screens/Read/SegmentedMacrosBarC
import { Validation, ValidationStatus } from 'utils/validation/types';
import Dialogs from 'components/Shared/Dialogs';
import { validateEntryInputs } from 'utils/validation/validateEntry';
import toSQLiteParams from 'utils/toSQLiteParams';

type Props = StaticScreenProps<{
foodId: number;
Expand Down Expand Up @@ -155,6 +156,7 @@ export default function Read({ route }: Props) {
<Portal.Host>
<Portal>
<Dialogs show={showDialogs} setShow={setShowDialogs} errors={validation.errors} />
{/* TODO: add confirmation dialog for deletion */}
</Portal>
<KeyboardAwareScrollView
behavior="padding"
Expand Down

0 comments on commit 91b793a

Please sign in to comment.