Skip to content

Fetch and Update any Company Logo in Gatsby

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.

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

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

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

  • An understanding of JavaScript and Gatsby

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:

node -v
v16.10.0 //node version installed

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

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

$ gatsby new {project-name}

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

$ 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/.

$ gatsby develop

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:

    .column {
      float: left;
      width: 33.33%;
      padding: 5px;
    }
    /* Clear floats after image containers */
    .row::after {
      content: "";
      clear: both;
      display: table;
    }
Code language: CSS (css)

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

    import React, { useState, useEffect } from "react"
    import "../styles/index.css"
    
    function App() {
      return (
        <div className="row">
          
        </div>
      )
    }
    export default App
Code language: JavaScript (javascript)

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:

API_KEY=<API-KEY>

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

    require("dotenv").config({
      path: `.env.${process.env.NODE_ENV}`,
    })
    
    module.exports = {
    ...
Code language: JavaScript (javascript)

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.

    import fetch from "node-fetch"
    
    export default async function fetchLogos(req, res) {
      const url = "https://api.brandfetch.io/v2/brands"
      const headers = {
        "Content-Type": "application/json",
        Authorization: `Bearer ${process.env.API_KEY}`,
      }
    
      const companies = ["facebook", "twitter", "amazon"]
    
      try {
        let logos = await Promise.all(
          companies.map(async company => {
            const result = await fetch(`${url}/${company}.com`, {
              method: "GET",
              headers: headers,
            }).then(res => {
              return res.json()
            })
            return result.logos[0].formats[1].src
          })
        )
    
        res.json(logos)
      } catch (error) {
        res.status(500).send(error)
      }
    }
Code language: JavaScript (javascript)

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.

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.

    import React, { useState, useEffect } from "react"
    import "../styles/index.css"
    
    function App() {
      const [data, setData] = useState([])
    
      useEffect(() => {
        async function fetchData() {
          const result = await fetch(`/api/logo`).then(res => res.json())
          setData(result)
        }
        fetchData()
      }, [])
    
      return (
      ...
Code language: JavaScript (javascript)

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

      ...
      return (
        <div className="row">
          {data.length > 0
            ? data.map(logo => (
                <div className="column" key={logo}>
                  <img src={logo} alt={logo} width="50%" height="50%"/>
                </div>
              ))
            : ""}
        </div>
      )
    ...
Code language: HTML, XML (xml)

The result looks like this:

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

Back to top

Featured Post