diff --git a/locales/en/allLaunches.json b/locales/en/allLaunches.json
index 9dd5e55..4018d43 100644
--- a/locales/en/allLaunches.json
+++ b/locales/en/allLaunches.json
@@ -4,5 +4,9 @@
"title": "Lançamentos",
"description": "Acompanhe os lançamentos e os dados de cada missão."
}
+ },
+ "actions": {
+ "refresh": "Refresh launches",
+ "refreshSuccess": "Data updated"
}
}
diff --git a/locales/es/allLaunches.json b/locales/es/allLaunches.json
index 9dd5e55..935fb20 100644
--- a/locales/es/allLaunches.json
+++ b/locales/es/allLaunches.json
@@ -4,5 +4,9 @@
"title": "Lançamentos",
"description": "Acompanhe os lançamentos e os dados de cada missão."
}
+ },
+ "actions": {
+ "refresh": "Actualizar lanzamientos",
+ "refreshSuccess": "Datos actualizados"
}
}
diff --git a/locales/pt/allLaunches.json b/locales/pt/allLaunches.json
index 628406d..e1f8a0e 100644
--- a/locales/pt/allLaunches.json
+++ b/locales/pt/allLaunches.json
@@ -12,5 +12,9 @@
"title": "Lançamentos",
"description": "Acompanhe os lançamentos e os dados de cada missão."
}
+ },
+ "actions": {
+ "refresh": "Atualizar lançamentos",
+ "refreshSuccess": "Dados atualizados"
}
}
diff --git a/pages/launches/index.tsx b/pages/launches/index.tsx
index be686af..35d3d32 100644
--- a/pages/launches/index.tsx
+++ b/pages/launches/index.tsx
@@ -1,8 +1,9 @@
-import { useEffect } from 'react';
+import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { useAllLaunches } from '@/src/core/services/launches/useGetAllLaunches.service';
import { slugifyLaunchName } from '@/src/shared/utils/formatters.utils';
-import { Alert, Box, CircularProgress, Container, Stack, Typography } from '@mui/material';
+import { Alert, Box, Button, CircularProgress, Container, Snackbar } from '@mui/material';
+import RefreshIcon from '@mui/icons-material/Refresh';
import type {} from '@mui/lab/themeAugmentation';
import useTranslation from 'next-translate/useTranslation';
import LaunchSummaryCard from '@/src/components/LaunchCard/LaunchSummaryCard';
@@ -17,9 +18,22 @@ const SCROLL_POSITION_KEY = 'zenith-launches-scroll';
// TODO mover textos para arquivo de tradução
export default function LaunchesPage() {
- const { launches, isLoadingAllLaunches, error } = useAllLaunches();
+ const { launches, isLoadingAllLaunches, isRefreshingLaunches, refreshLaunches, error } = useAllLaunches();
const router = useRouter();
const { t } = useTranslation();
+ const [isRefreshSnackbarOpen, setIsRefreshSnackbarOpen] = useState(false);
+
+ const handleRefreshLaunches = async () => {
+ const succeeded = await refreshLaunches();
+ if (succeeded) {
+ setIsRefreshSnackbarOpen(true);
+ }
+ };
+
+ const handleCloseRefreshSnackbar = (_event?: React.SyntheticEvent | Event, reason?: string) => {
+ if (reason === 'clickaway') return;
+ setIsRefreshSnackbarOpen(false);
+ };
useEffect(() => {
if (isLoadingAllLaunches || launches.length === 0) return;
@@ -61,6 +75,19 @@ export default function LaunchesPage() {
/>
+ {!isLoadingAllLaunches && (
+
+ : }
+ >
+ {t(LOCALE.LAUNCHES.ACTIONS.REFRESH)}
+
+
+ )}
+
{error && (
{error}
@@ -89,13 +116,27 @@ export default function LaunchesPage() {
)}
+
+
+
+ {t(LOCALE.LAUNCHES.ACTIONS.REFRESH_SUCCESS)}
+
+
>
);
}
const pageBackgroundSx = { backgroundColor: BACKGROUND_COLOR };
const containerSx = { py: 6 };
+const toolbarSx = { display: 'flex', justifyContent: 'flex-end', mb: 3 };
const errorAlertSx = { mb: 3 };
+const snackbarAnchorOrigin = { vertical: 'bottom', horizontal: 'center' } as const;
+const snackbarAlertSx = { width: '100%' };
const loadingBoxSx = { display: 'flex', justifyContent: 'center', py: 10 };
const launchesGridSx = {
display: 'grid',
diff --git a/src/core/api/launches/launches-api.service.ts b/src/core/api/launches/launches-api.service.ts
index 34beed6..6d19e29 100644
--- a/src/core/api/launches/launches-api.service.ts
+++ b/src/core/api/launches/launches-api.service.ts
@@ -1,8 +1,21 @@
import { environment } from '@/src/environments/environment';
import { LaunchRecord, LaunchSummary } from '@/src/shared/types/api/launches-api.types';
-export const getAllLaunches = async (signal?: AbortSignal): Promise => {
- const response = await fetch(environment.launchesEndpoints.launches.all, { signal });
+type GetAllLaunchesApiOptions = {
+ signal?: AbortSignal;
+ bypassCache?: boolean;
+};
+
+export const getAllLaunches = async ({ signal, bypassCache = false }: GetAllLaunchesApiOptions = {}): Promise<
+ LaunchSummary[]
+> => {
+ const url = new URL(environment.launchesEndpoints.launches.all);
+ if (bypassCache) {
+ // O GitHub Pages responde com max-age=600: sem isso o navegador/CDN devolvem a resposta em cache.
+ url.searchParams.set('t', String(Date.now()));
+ }
+
+ const response = await fetch(url, { signal, cache: bypassCache ? 'no-store' : 'default' });
if (!response.ok) {
throw new Error('Failed to fetch launches data');
}
diff --git a/src/core/services/launches.service.ts b/src/core/services/launches.service.ts
index d1cb26c..a26adc5 100644
--- a/src/core/services/launches.service.ts
+++ b/src/core/services/launches.service.ts
@@ -3,9 +3,21 @@ import {
getLaunchContent as getLaunchContentApi
} from '@/src/core/api/launches/launches-api.service';
import { LaunchRecord, LaunchSummary } from '@/src/shared/types/api/launches-api.types';
+import { readCachedLaunches, saveCachedLaunches } from './launches/launchesCache';
-export const getAllLaunches = async (): Promise => {
- return getAllLaunchesApi();
+type GetAllLaunchesOptions = {
+ forceRefresh?: boolean;
+};
+
+export const getAllLaunches = async ({ forceRefresh = false }: GetAllLaunchesOptions = {}): Promise => {
+ if (!forceRefresh) {
+ const cached = readCachedLaunches();
+ if (cached) return cached;
+ }
+
+ const data = await getAllLaunchesApi({ bypassCache: forceRefresh });
+ saveCachedLaunches(data);
+ return data;
};
export const getLaunchContent = async (downloadUrl: string): Promise => {
diff --git a/src/core/services/launches/launchesCache.ts b/src/core/services/launches/launchesCache.ts
new file mode 100644
index 0000000..bb74f3b
--- /dev/null
+++ b/src/core/services/launches/launchesCache.ts
@@ -0,0 +1,45 @@
+import { LaunchSummary } from '@/src/shared/types/api/launches-api.types';
+
+export const LAUNCHES_STORAGE_KEY = 'zenith-launches';
+export const LAUNCHES_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
+
+type CachedLaunches = {
+ savedAt: number;
+ data: LaunchSummary[];
+};
+
+const isStorageAvailable = () => typeof window !== 'undefined' && Boolean(window.localStorage);
+
+export const readCachedLaunches = (): LaunchSummary[] | null => {
+ if (!isStorageAvailable()) return null;
+
+ try {
+ const raw = localStorage.getItem(LAUNCHES_STORAGE_KEY);
+ if (!raw) return null;
+
+ const parsed: CachedLaunches = JSON.parse(raw);
+ const isValid = Array.isArray(parsed?.data) && typeof parsed?.savedAt === 'number';
+ const isExpired = Date.now() - parsed.savedAt > LAUNCHES_CACHE_TTL_MS;
+
+ if (!isValid || isExpired) {
+ localStorage.removeItem(LAUNCHES_STORAGE_KEY);
+ return null;
+ }
+
+ return parsed.data;
+ } catch {
+ localStorage.removeItem(LAUNCHES_STORAGE_KEY);
+ return null;
+ }
+};
+
+export const saveCachedLaunches = (data: LaunchSummary[]) => {
+ if (!isStorageAvailable()) return;
+
+ try {
+ const payload: CachedLaunches = { savedAt: Date.now(), data };
+ localStorage.setItem(LAUNCHES_STORAGE_KEY, JSON.stringify(payload));
+ } catch {
+ // Storage cheio ou indisponível (ex.: modo privado): segue sem cache.
+ }
+};
diff --git a/src/core/services/launches/useGetAllLaunches.service.ts b/src/core/services/launches/useGetAllLaunches.service.ts
index 9f77541..78b1fec 100644
--- a/src/core/services/launches/useGetAllLaunches.service.ts
+++ b/src/core/services/launches/useGetAllLaunches.service.ts
@@ -1,43 +1,53 @@
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useCallback, useRef } from 'react';
import { LaunchSummary } from '@/src/shared/types/api/launches-api.types';
import { getAllLaunches } from '../launches.service';
export const useAllLaunches = () => {
const [launches, setLaunches] = useState([]);
const [isLoadingAllLaunches, setIsLoadingAllLaunches] = useState(true);
+ const [isRefreshingLaunches, setIsRefreshingLaunches] = useState(false);
const [error, setError] = useState(null);
+ const isMountedRef = useRef(true);
- useEffect(() => {
- const controller = new AbortController();
-
- const fetchLaunches = async () => {
- setIsLoadingAllLaunches(true);
- setError(null);
-
- try {
- const rawData = await getAllLaunches();
- if (!controller.signal.aborted) {
- setLaunches(rawData);
- }
- } catch (err) {
- if (err instanceof Error && err.name === 'AbortError') {
- return;
- }
+ const fetchLaunches = useCallback(async (forceRefresh: boolean): Promise => {
+ setError(null);
+ try {
+ const rawData = await getAllLaunches({ forceRefresh });
+ if (isMountedRef.current) {
+ setLaunches(rawData);
+ }
+ return true;
+ } catch (err) {
+ if (isMountedRef.current) {
setError(err instanceof Error ? err.message : 'Ocorreu um erro inesperado');
- } finally {
- if (!controller.signal.aborted) {
- setIsLoadingAllLaunches(false);
- }
}
- };
+ return false;
+ }
+ }, []);
- fetchLaunches();
+ useEffect(() => {
+ isMountedRef.current = true;
+
+ fetchLaunches(false).finally(() => {
+ if (isMountedRef.current) {
+ setIsLoadingAllLaunches(false);
+ }
+ });
return () => {
- controller.abort();
+ isMountedRef.current = false;
};
- }, []);
-
- return { launches, isLoadingAllLaunches, error };
+ }, [fetchLaunches]);
+
+ const refreshLaunches = useCallback(async (): Promise => {
+ setIsRefreshingLaunches(true);
+ const succeeded = await fetchLaunches(true);
+ if (isMountedRef.current) {
+ setIsRefreshingLaunches(false);
+ }
+ return succeeded;
+ }, [fetchLaunches]);
+
+ return { launches, isLoadingAllLaunches, isRefreshingLaunches, refreshLaunches, error };
};
diff --git a/src/shared/consts/locales.const.ts b/src/shared/consts/locales.const.ts
index b6e72d8..2586174 100644
--- a/src/shared/consts/locales.const.ts
+++ b/src/shared/consts/locales.const.ts
@@ -6,6 +6,10 @@ export const LAUNCHES = {
TITLE: 'allLaunches:metaTags.title',
DESCRIPTION: 'allLaunches:metaTags.description',
SUBTITLE: 'allLaunches:metaTags.subtitle'
+ },
+ ACTIONS: {
+ REFRESH: 'allLaunches:actions.refresh',
+ REFRESH_SUCCESS: 'allLaunches:actions.refreshSuccess'
}
} as const;