diff --git a/.env.template b/.env.template index a3ac516..a99265e 100644 --- a/.env.template +++ b/.env.template @@ -1,4 +1,5 @@ -# A template for the file that would store secrets (e.g. environment variables) -# copy this to your .env file and add your own API key etc +# copy this file and rename it as .env +# this needs to be in youre root directory +# replace with your api key -NASA-API-KEY=add-your-key-here \ No newline at end of file +REACT_APP_NASA_API_KEY="" \ No newline at end of file diff --git a/src/App.tsx b/src/App.tsx index 29788f9..ae13588 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import {BrowserRouter as Router, Routes, Route} from 'react-router-dom'; +import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; import './App.scss'; import Home from './Home/Home'; import Header from './header'; diff --git a/src/images/DisplayPicture.tsx b/src/images/DisplayPicture.tsx new file mode 100644 index 0000000..bc3d4d0 --- /dev/null +++ b/src/images/DisplayPicture.tsx @@ -0,0 +1,46 @@ +import React, { useState, useEffect } from 'react'; +import { fetchAPI } from '../utils/fetchData'; + +interface PictureOfDay { + date: string, + explanation: string, + hdurl: string, + title: string, + url: string +} + +export const DisplayPictureOfDay = () => { + const [myPictureData, setMyPictureData] = useState(null); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + const FetchPicture = async () => { + + try { + setIsLoading(true); + + const pictureData = await fetchAPI("https://api.nasa.gov/planetary/apod?api_key="); + + setMyPictureData(pictureData); + setIsLoading(false); + + } catch (err: unknown) { + if (err instanceof Error) { + setError(err); // Set the actual Error object + } else { + setError(new Error('An unknown error occurred')); // Provide a default Error object + } + + setIsLoading(false); + } + } + useEffect(() => { + FetchPicture(); + }, []) + + if (isLoading) return (
Is Loading...
); + if (error) return (
{error.message}
); + if (!myPictureData) return (
EMPTY
); + + return myPictureData; +}; \ No newline at end of file diff --git a/src/utils/fetchData.ts b/src/utils/fetchData.ts new file mode 100644 index 0000000..8ce7409 --- /dev/null +++ b/src/utils/fetchData.ts @@ -0,0 +1,20 @@ +// 1. .env has to be created in root +// 2. inside .env, it should be REACT_APP_NASA_API_KEY="" + +export async function fetchAPI(apiUrl: string) { + const apiKey = process.env.REACT_APP_NASA_API_KEY; + const link = `${apiUrl}${apiKey}`; + + try { + const response = await fetch(link); + if (!response.ok) { + throw new Error('Network response was not ok'); + } + + const pictureData = await response.json(); + console.log(pictureData); + return pictureData; + } catch (err) { + throw err; + } +} \ No newline at end of file