This guide shows you how to fetch data from a 3rd party API and display that data within one of your components.
- Create a new server route
This route sits between your front-end code and the 3rd party API, allowing you to keep the API endpoint and key secret. In the below example we use the fetch
function, but if the 3rd party API has its own Node.js library then you’ll want to use that instead.
// api/city.js
const fetch = require("node-fetch");
export default async (req, res) => {
// Get query parameter
const { cityName } = req.query;
// Fetch data from 3rd party API
const data = await fetch(`https://cityapi.com/${cityName}?apiKey=12345`)
.then(response => response.json());
// Return response with data
return res.send({
status: "success",
data: data,
});
};
- Fetch and display data within a component
We make a request to the above server route and utilize the React Query library so that we can fetch right in our component body and track the status of the request.
import { useQuery } from "react-query";
import { apiRequest } from "./../util";
function CityInfo(props){
// Use React Query to fetch with a React hook
// Learn more: https://tanstack.com/query/v4/docs/overview
const { data, status } = useQuery(
['city', { name: props.cityName }], // Unique key
() => apiRequest(`city?cityName=${props.cityName}`)
);
if (status === "loading"){
return "loading...";
}
return (
<div>City population: {data.population}</div>
);
}
2 (alternate). Or you can fetch data from the 3rd party API directly from your frontend code
Only do this if the 3rd party API does not require a secret API key. Even so, if the API does not allow cross-domain requests you may find you still need to go through a server route.
import { useQuery } from "react-query";
import { apiRequestExternal } from "./../util";
function CityInfo(props){
// Use React Query to fetch with a React hook
// Learn more: https://tanstack.com/query/v4/docs/overview
const { data, status } = useQuery(
['city', { name: props.cityName }], // Unique key
() => apiRequestExternal(`https://cityapi.com/${cityName}`)
);
if (status === "loading"){
return "loading...";
}
return (
<div>City population: {data.population}</div>
);
}