Skip to content

Commit

Permalink
feat: sync feature
Browse files Browse the repository at this point in the history
  • Loading branch information
Th0rgal committed Dec 13, 2024
1 parent c4f0dd0 commit 7d0decc
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
18 changes: 13 additions & 5 deletions shared/MealsStorageContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,13 @@ export const MealsDatabaseProvider: React.FC<ProviderProps> = ({
const syncMeals = async () => {
try {
const lastSync = await getLastSyncTimestamp();
if (!lastSync) return;
if (!lastSync) {
// If no last sync, use a timestamp from 24 hours ago
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
await setLastSyncTimestamp(yesterday.toISOString());
return;
}

const response = await fetch(
`https://api.calorily.com/meals/sync?since=${lastSync}`,
Expand Down Expand Up @@ -451,7 +457,7 @@ export const MealsDatabaseProvider: React.FC<ProviderProps> = ({
}
};

// Call sync when app becomes active
// Call sync when app becomes active or resumes from background
useEffect(() => {
const subscription = AppState.addEventListener("change", (nextAppState) => {
if (nextAppState === "active") {
Expand All @@ -462,12 +468,14 @@ export const MealsDatabaseProvider: React.FC<ProviderProps> = ({
return () => {
subscription.remove();
};
}, []);
}, [jwt]); // Add jwt as dependency

// Initial sync when component mounts
useEffect(() => {
syncMeals();
}, []);
if (jwt) {
syncMeals();
}
}, [jwt]);

const addMeal = async (imageUri: string, mealId: string) => {
try {
Expand Down
2 changes: 1 addition & 1 deletion shared/WebSocketContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export function WebSocketProvider({ children }: { children: React.ReactNode }) {
if (lastMessage.event === "analysis_failed") {
mealService.updateMeal({
meal_id: lastMessage.meal_id,
status: "failed",
status: "error",
error_message: lastMessage.error,
});
} else if (lastMessage.event === "analysis_complete") {
Expand Down

0 comments on commit 7d0decc

Please sign in to comment.