Skip to content

Commit

Permalink
Merge pull request #17 from techswitch-learners/mm-402-random-image
Browse files Browse the repository at this point in the history
MM-402 Random Image
  • Loading branch information
natashabuckham committed Aug 1, 2024
2 parents bf8f521 + c2b7236 commit a189189
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
46 changes: 46 additions & 0 deletions src/images/DisplayRandomPicture.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import React, { useState, useEffect } from 'react';
import { fetchRandomAPI } from '../utils/fetchData';

interface RandomPicture {
date: string,
explanation: string,
hdurl: string,
title: string,
url: string
}

export const DisplayRandomPicture = () => {
const [myPictureData, setMyPictureData] = useState<Array<RandomPicture> | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);

const FetchPicture = async () => {

try {
setIsLoading(true);

const pictureData = await fetchRandomAPI("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 (<div>Is Loading...</div>);
if (error) return (<div>{error.message}</div>);
if (!myPictureData) return (<div>EMPTY</div>);

return myPictureData;
};
19 changes: 18 additions & 1 deletion src/utils/fetchData.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// 1. .env has to be created in root
// 2. inside .env, it should be REACT_APP_NASA_API_KEY="<your api key>"


const year = new Date().getFullYear()
const month = (new Date().getMonth()) + 1
const date = new Date().getDate()
Expand All @@ -11,6 +10,24 @@ export async function fetchAPI(apiUrl: string, date = todaysDate) {
const apiKey = process.env.REACT_APP_NASA_API_KEY;
const link = `${apiUrl}${apiKey}&date=${date}`;

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;
}
}

export async function fetchRandomAPI(apiUrl: string) {
const apiKey = process.env.REACT_APP_NASA_API_KEY;
const link = `${apiUrl}${apiKey}&count=1`;

try {
const response = await fetch(link);
if (!response.ok) {
Expand Down

0 comments on commit a189189

Please sign in to comment.