From 329ee7afa5b9930937b23a5955f8255171eafb94 Mon Sep 17 00:00:00 2001 From: ChrQR Date: Sat, 18 May 2024 01:02:29 +0200 Subject: [PATCH] added error handling to getlocation function --- app/actions.ts | 41 +++++++++++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/app/actions.ts b/app/actions.ts index 211561c..3ec9904 100644 --- a/app/actions.ts +++ b/app/actions.ts @@ -1,21 +1,38 @@ "use server"; + import { Forecast, LocationType, coordType } from "@/types/types"; -//takes address and returns coords in obj as {lat: number, lng: number} export async function getLocation(searchLocation: string): Promise { - const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${searchLocation}&key=${process.env.PLACES_API}`; - const res = await fetch(url); - if (!res.ok) { - throw new Error(`There was an error fetching the data`); + const placesKey = process.env.PLACES_API; + if (!placesKey) { + console.error("PLACES_API environment variable is not set"); + throw new Error("PLACES_API environment variable is not set"); } - const data: LocationType = await res.json(); - if (!data.results[0].formatted_address) { - throw new Error(`Unable to find the address`); + + const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${searchLocation}&key=${placesKey}`; + console.log(`Fetching URL: ${url}`); + + try { + const res = await fetch(url); + if (!res.ok) { + console.error(`Fetch error: ${res.statusText}`); + throw new Error(`There was an error fetching the data`); + } + + const data: LocationType = await res.json(); + if (!data.results[0]?.formatted_address) { + console.error("Unable to find the address in the response"); + throw new Error(`Unable to find the address`); + } + + return { + name: data.results[0].formatted_address, + geo: data.results[0].geometry.location, + }; + } catch (error) { + console.error("Error fetching location:", error); + throw new Error("Error fetching location"); } - return { - name: data.results[0].formatted_address, - geo: data.results[0].geometry.location, - }; } export async function getHourlyForecast(