Fetching Data using Headers

Making an API call without headers can be done right in the code fence of an Astro file.

But, if you need to use headers, for example to include an API token, then the data will have to be fetched in a component, and the component rendered in your .astro file.

Fetching data from an API call with token in header

Fetch is performed in the component

Get a list of recently-observed birds in your area!

Current location set:

Reported in the last 14 days...

The code for this page:

---
import BaseLayout from '../../layouts/BaseLayout.astro';
import { Markdown } from 'astro/components'
import BirdFetchComponent from '../../components/experiments/BirdFetchComponent.jsx';
---
<BaseLayout title="Fetching Data from an API using Headers" >
<main>
<h1>Fetching Data using Headers</h1>
<p>Making an API call without headers can be done right in the code fence of an Astro file.</p>
<p>But, if you need to use headers, for example to include an API token, then the data will have to be fetched in a component, and the component rendered in your .astro file.</p>

<h2>Fetching data from an API call with token in header</h1>
<h3>Fetch is performed in the component</h3>
<BirdFetchComponent client:load />
</main>
</BaseLayout />

And the code from the component (to come, trouble shooting new Markdown rendering issues!)


//src/components/BirdFetchComponent.jsx
import React from "react";
import { useState } from "react";

export default function BirdFetchComponent() {
const [recentBirds, setRecentBirds] = useState([]);
const [location, setLocation] = useState("");

async function getBirdSightings(event) {
event.preventDefault();
setLocation(event.target.elements.location.value.toUpperCase());
const queryLocation = event.target.elements.location.value.toUpperCase();
const recentUrl = \`https://api.ebird.org/v2/data/obs/${queryLocation}/recent?back=14\`;
const myHeaders = new Headers();
myHeaders.append("X-eBirdApiToken", "+0k3Ns+rInG");

const requestOptions = {
method: "GET",
headers: myHeaders,
redirect: "follow"
};
const response = await fetch(recentUrl, requestOptions);
const data = await response.json();
setRecentBirds(data);
}

return (
<>
<h3>Get a list of recently-observed birds in your area!</h3>
<h5 className="birdtab">Current location set: {location} </h5>

<form onSubmit={getBirdSightings}>
<input
name="location"
type="text"
placeholder="eBird region ID eg. CA-PE"
style={{ textTransform: "uppercase" }}
/>
<button> See the birds!</button>
</form>

<h3>Reported in the last 14 days...</h3>
{recentBirds.map((bird) => (
<p> 
{bird.howMany} {bird.comName}(s) seen at {bird.obsDt.toString().slice(11)} on {bird.obsDt.toString().slice(5,10)}
</p>
))}
</>
);
}