Skip to content
Advertisement

how to reverse fetch images from nasa APOD api in react

** I fetched content from API with this code**

    import React from "react";
import styles from "./Space.module.css";

import {useState,useEffect} from "react";
function Space() {
  const [photoData,setPhotoData]=useState(null);
  useEffect(()=>{
fetchPhoto();
async function fetchPhoto(){
  const res = await fetch(`https://api.nasa.gov/planetary/apod?api_key=hETQq0FPsZJnUP9C3sUEFtwmJH3edb4I5bghfWDM`);
  const data=await res.json();
  setPhotoData(data);
  console.log(data);
}
  },[]); //empty array for running only once then empty array for that 
 

  if (!photoData) return <div />;
  
  return (
    <>
    <div className={styles.space}>
      {photoData.media_type === "image" ? (
        <img 
          src={photoData.url}
          alt={photoData.title}
          className={styles.space}
        />
      ) : (
        <iframe
          title="space-video"
          src={photoData.url}
          frameBorder="0"
          gesture="media"
          allow="encrypted-media"
          allowFullScreen
          className={styles.space}
        />
      )}
      <div>
        <h1>{photoData.title}</h1>
        <p className={styles.space.date}>{photoData.date}</p>
        <p className={styles.space.explanation}>{photoData.explanation}</p>
      </div>
      
    </div>
    </>
  );
}
export default Space;

and output of this code is like this enter image description here and I want Button here with next and then that will show previous day images so can anyone tell me how to reverse that means after clicking on the next button by reversing the previous day images will show because NASA APOD(astronomy picture of the day )daily shown to all users like that is updated daily I know we can reverse that but can anyone tell me how to do that?

Advertisement

Answer

You can use date query parameter of apod api to get data for a specific date. This has default value today. Date needs to be in YYYY-MM-DD format. See apod section at https://api.nasa.gov/

If you want to request data for 2 January 2021 you’ll have to send request to this :

https://api.nasa.gov/planetary/apod?date=2021-01-02&api_key=hETQq0FPsZJnUP9C3sUEFtwmJH3edb4I5bghfWDM

Note the date parameter

To get the previous day date use :

let today = new Date();
let yesterday = new Date();

yesterday.setDate(today.getDate() - 1);
console.log(yesterday.toString());

for formatting date in YYYY-MM-DD format see this question.

In onClick function of your button you’ll make this http request and then change state with setPhotoData function.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement