Pulling MetaData/getting an api with a key for ReactJS

Viewed 28

So I'm still new to react and just learned about api and i have google how to pull the metadata but im struggling to find an solution or and little bit of info to help me to be able to get the below to work for my react. Thanks

$.get({
  url: 'https://example.com/products'
  headers: { 'Authorization': 'Token <key>' },
  contentType: 'application/vnd.api+json'
});
1 Answers

If I am getting you right you just struggle to call an API in ReactJS?

First I would give you the Advice to use Postman ( https://www.postman.com/ ) whenever you need to work with an API. In Postman you can easily test API´s send different types of requests etc. Also if your request then works in Postman they provide a sample code in a variety of programming languages. So this is one of my most important tools since I started with API´s.

My second Advice would be use a JSON parser. I use a chrome extension its called "JSON Viewer Pro" https://chrome.google.com/webstore/detail/json-viewer-pro/eifflpmocdbdmepbjaopkkhbfmdgijcc This helps you to figure out what path you need to provide for the element you need of your response data. It formates the JSON in a way where you can very well understand it. And if you click on the element you need you can copy the path to it all in your browser.

And last Advice is to use Axios Module ( https://www.npmjs.com/package/axios ) to make your request instead of the built in fetch. You need to install it with "npm i --save axios" or "yarn add axios".

I want to give you a quick example code maybe that helps to clearify things further. In this example i use a NASA API. You can get a api key from https://api.nasa.gov/ for free. In this API there is no Authorization header needed since we provide the API Key as query parameter. Also css classNames are related to semantic UI.

import React,{useEffect,useState} from 'react'
import axios from "axios";

const App = () => {
  const [photos,setPhotos] = useState([]);
  useEffect(() => {
    const requestNASAphotos = async () => {
      const API_KEY = ""
      const res = await axios({ method: "get", url: `https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?earth_date=2022-07-27&api_key=${API_KEY}` });
      if (res.data !== "undefined") {
        console.log(`res.data ${JSON.stringify(res.data)}`);
        if (res.data.length === 0){
            setPhotos([])
        }else{
            setPhotos(res.data.photos)
        }
        
      } else  setPhotos([]);
    };
    requestNASAphotos()
  }, []);
  const renderedPhotos = photos.map((photo, i) => {
    return (
      <div key={photos.id} className="card">
        <div className="image"><img src={photo.img_src} alt={photos.id}></img></div>
        <div className="content">
          <div className="header">{photo.name}</div>
          <div className="meta">{photo.camera.full_name}</div>
          <div className="description">Earth Date: {photo.earth_date}</div>
        </div>
        <div className="extra content">{photo.rover.name}</div>
      </div>
    );
  });
  return (
    <div className="ui container">
    {renderedPhotos}
    </div>
  );
}

export default App;
Related