Fetch and Update any Company Logo in Gatsby

Tosin Moronfolu

Introduction

Fetching data in Gatsby has been made easy using Gatsby Functions. Gatsby Functions enable us to build Express-like backends without running any servers.

In this article, we’ll learn how to use Gatsby Functions to make API calls and get a response in our Gatsby App.

Sandbox

The completed project is on CodeSandbox. Fork it and run the code.

GitHub repository

https://github.com/folucode/fetch-company-logos-gatsbyjs

Prerequisites

To follow along with this article, you’ll need to have:

  • An understanding of JavaScript and Gatsby

Project setup

Node and its package manager npm are required to initialize a new project.

To install Node, go to the Nodejs website and follow the instructions. Then, verify its installation using the terminal command below:

1node -v
2v16.10.0 //node version installed

The result shows the version of Node.js we installed on our computer.

Create a Gatsby project

We’ll create a new Gatsby application using the code below. This will create a new boilerplate app using Gatsby’s default starter template.

1$ gatsby new {project-name}

After successful installation, navigate into the app directly, like so:

1$ cd {project-name}

Inside the new app directory, start the app using the code below. This will create a development server on http://localhost:8000/.

1$ gatsby develop

Creating the application

First, let’s do a basic setup. Create a new folder in the src folder called styles, and in it, create a new file called index.css. Paste the code below into that file:

1.column {
2 float: left;
3 width: 33.33%;
4 padding: 5px;
5 }
6 /* Clear floats after image containers */
7 .row::after {
8 content: "";
9 clear: both;
10 display: table;
11 }

Next, in the index.js file in the page``s folder, replace the boilerplate code with the code below:

1import React, { useState, useEffect } from "react"
2 import "../styles/index.css"
3
4 function App() {
5 return (
6 <div className="row">
7
8 </div>
9 )
10 }
11 export default App

Setting up Gatsby Function

To fetch the company logos, we’ll need an API that can give us that information, and for this article, we’ll be using brandfetch. Create an account by going to brandfetch and then clicking on the Get API Key button at the top right corner of the screen.

Now, we’ll need to store the API key in an env file for security reasons. To use env files in our logo.js file, we first need to create a .env.development file at the root of our project and enter our API key like so:

1API_KEY=<API-KEY>

Then, in the gatsby-config.js file, paste the code below at the top of the file before any other syntax.

1require("dotenv").config({
2 path: `.env.${process.env.NODE_ENV}`,
3 })
4
5 module.exports = {
6 ...

Note: Be sure to restart the development server after this process.

After that, in the src folder, we'll create an api folder with a logo.js file inside it. Open the newly created logo.js file and paste the code below.

1import fetch from "node-fetch"
2
3 export default async function fetchLogos(req, res) {
4 const url = "https://api.brandfetch.io/v2/brands"
5 const headers = {
6 "Content-Type": "application/json",
7 Authorization: `Bearer ${process.env.API_KEY}`,
8 }
9
10 const companies = ["facebook", "twitter", "amazon"]
11
12 try {
13 let logos = await Promise.all(
14 companies.map(async company => {
15 const result = await fetch(`${url}/${company}.com`, {
16 method: "GET",
17 headers: headers,
18 }).then(res => {
19 return res.json()
20 })
21 return result.logos[0].formats[1].src
22 })
23 )
24
25 res.json(logos)
26 } catch (error) {
27 res.status(500).send(error)
28 }
29 }

We are taking these steps in this file:

  1. Import fetch from node-fetch to query the brandfetch API endpoint. After that, we export a single function that accepts two parameters: req (Node’s request object) and res (Node’s response object).
  2. Set the brandfetch API base URL in a variable, and then set the necessary headers. The Authorization header is needed to authenticate the API. Put the names of the companies we want to show in an array.

Note: The API key can be found on the dashboard.

  1. Map through our array of companies and obtain their data using the fetch API. After looping, we'll send the result using Node's response object.

Displaying the result

Now, in the index.js file in the page``s folder, we’ll query our logo endpoint in a useEffect hook to get the data once our page loads. After that, save the response in the state.

1import React, { useState, useEffect } from "react"
2 import "../styles/index.css"
3
4 function App() {
5 const [data, setData] = useState([])
6
7 useEffect(() => {
8 async function fetchData() {
9 const result = await fetch(`/api/logo`).then(res => res.json())
10 setData(result)
11 }
12 fetchData()
13 }, [])
14
15 return (
16 ...

Next, we display the results on our page once we have them in our state variable, like so:

1...
2 return (
3 <div className="row">
4 {data.length > 0
5 ? data.map(logo => (
6 <div className="column" key={logo}>
7 <img src={logo} alt={logo} width="50%" height="50%"/>
8 </div>
9 ))
10 : ""}
11 </div>
12 )
13 ...

The result looks like this:

Conclusion

This article taught us how to use Gatsby Functions to fetch data and render them.

Resources

Tosin Moronfolu

Software Engineer

I'm a software engineer with hands-on experience in building robust and complex applications improving performance and scalability. I love everything tech and science, especially physics and maths. I also love to read books, mainly non-fiction, and I love music; I play the guitar.