diff options
| -rw-r--r-- | Backend/ListStops.cs | 9 | ||||
| -rw-r--r-- | src/pages/Home.tsx | 17 |
2 files changed, 18 insertions, 8 deletions
diff --git a/Backend/ListStops.cs b/Backend/ListStops.cs index 93b6a48..b6f9ab4 100644 --- a/Backend/ListStops.cs +++ b/Backend/ListStops.cs @@ -2,6 +2,7 @@ using Microsoft.Azure.Functions.Worker; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Costasdev.VigoTransitApi; +using Costasdev.VigoTransitApi.Types; namespace Costasdev.UrbanoVigoWeb; @@ -9,6 +10,8 @@ public class ListStops { private readonly VigoTransitApiClient _api; + public List<Stop>? Stops { get; set; } = null; + public ListStops(HttpClient http) { _api = new VigoTransitApiClient(http); @@ -17,6 +20,12 @@ public class ListStops [Function("ListStops")] public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req) { + // Get stops from cache + if (Stops != null) + { + return new OkObjectResult(Stops); + } + try { var stops = await _api.GetStops(); diff --git a/src/pages/Home.tsx b/src/pages/Home.tsx index 14d5d7a..f92847a 100644 --- a/src/pages/Home.tsx +++ b/src/pages/Home.tsx @@ -10,20 +10,19 @@ interface Stop { } interface CachedStopList { - timetsamp: number; + timestamp: number; data: Stop[]; } export function Home() { const navigate = useNavigate() const { data, error, isLoading } = useSWR<Stop[]>('home', async () => { - const cachedData = localStorage.getItem('cachedStopList') - if (cachedData) { - const parsedData: CachedStopList = JSON.parse(cachedData) + const rawCachedData = localStorage.getItem('cachedStopList'); + if (rawCachedData) { + const parsedData: CachedStopList = JSON.parse(rawCachedData) // Cache for 12 hours - if (Date.now() - parsedData.timetsamp < 1000 * 60 * 60 * 12) { - console.log("parsed data: ", parsedData.data) + if (Date.now() - parsedData.timestamp < 1000 * 60 * 60 * 12) { return parsedData.data } else { localStorage.removeItem('cachedStopList') @@ -33,10 +32,12 @@ export function Home() { const response = await fetch('/api/ListStops') const body = await response.json(); - localStorage.setItem('cachedStopList', JSON.stringify({ + const cachedData: CachedStopList = { timestamp: Date.now(), data: body - })); + } + + localStorage.setItem('cachedStopList', JSON.stringify(cachedData)); return body; }); |
