Having trouble connecting to the Brewery API, could use some guidance from the experts (Novice)

I'm currently facing some difficulties connecting to a brewery API (). I am developing a webpage where users can input the city they are visiting and receive a list of breweries in that city. As someone unfamiliar with APIs, I am unsure about the necessary code modifications to display this on my site. Can anyone provide guidance on what might be going awry? Although likely a straightforward solution, I find myself somewhat disoriented at the moment.

const breweryName = document.querySelector(".brewery-name");
function getBrewery(name) {
console.log(data.name);
lat = lat.toString();
lon = lon.toString();
fetch(
 'https://api.openbrewerydb.org/breweries?by_city=princeton')    
 
 .then((response) => {
   response.json().then((data) => {
     const brewery = data.brewery;
     console.log(brewery);

     if (brewery.length === 0) {
       const breweryWarning = document.createElement("h3");
       breweryWarning.textContent = "Sorry, no breweries in that city!";
       breweryList.appendChild(brewerytWarning);
       return;
     }
     brewery.forEach((e) => {
       // creating date object and converting it to readable format
       let date = luxon.DateTime.fromISO(e.datetime_local).toLocaleString(
         luxon.DateTime.DATETIME_MED
       );
       const breweryItem = document.createElement("li");
       const breweryLink = document.createElement("a");
       const breweryImage = document.createElement("img");
       breweryLink.setAttribute("href", e.url);
       breweryImage.setAttribute("src", e.performers[0].images.huge);
       breweryLink.setAttribute("class", "event-block");
       breweryItem.textContent = `${e.title}- ${date}`;
       breweryLink.appendChild(breweryItem);
       breweryLink.appendChild(breweryImage);
       breweryList.appendChild(breweryLink);
     });
   });
 })
 .catch((err) => {
   console.log(err.message);
 });
}



Answer №1

Understanding the data returned by the API is crucial. The information does not include details about performances or images, and it refers to `website_url` instead of `url`.

I included a new element called `breweryList`, and I hope the provided code helps you with your project.

const breweryList = document.querySelector(".brewerylist");

function getBrewery(name) {

  const endpoint = `https://api.openbrewerydb.org/breweries?by_city=${name}`;

  fetch(endpoint)
    .then(response => response.json())
    .then(data => {;

      if (!data.length) {

        const breweryWarning = document.createElement('h3');
        breweryWarning.textContent = 'Sorry, no breweries in that city!';
        breweryList.appendChild(breweryWarning);

      } else {

        data.forEach(el => {

          const breweryItem = document.createElement('li');
          const breweryLink = document.createElement('a');
          
          breweryLink.setAttribute('href', el.website_url);
         
          breweryLink.setAttribute('class', 'event-block');
          breweryItem.textContent = el.name;
          breweryLink.appendChild(breweryItem);
        
          breweryList.appendChild(breweryLink);

        });

      }

    });

}

getBrewery('princeton');
<ul class="brewerylist"></ul>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using the keyof lookup in a Typescript interface is a powerful way to

I'm looking for a solution similar to: interface Operation<T, K extends keyof T> { key: keyof T; operation: 'add' | 'remove'; value: T[K]; } but without the necessity of passing K as a template. Essentially, I want to ...

Replicate a click using jQuery to retrieve a filtered multigallery based on the URL

I have a website that was built using Elementor for a photographer. The site features an Elementor Multigallery with a filter at the top. I am looking to create external links that will direct users to specific subpages showing only filtered items. For ex ...

Having trouble setting the audio source path in a handlebars file

homepage.html <script> function playAudio(audio_src){ console.log('audio src: ' + audio_src); var player = document.getElementById('player'); player.src = audio_src; player.load(); player.play(); return f ...

Adding content into a designated position in a document

My challenge is to find the index of user-provided data in order to insert new data at that specific point. I am familiar with array insertion methods, but extracting the index provided by the user is where I'm stuck. My current approach involves filt ...

Tips for adding a personalized close button to a Bootstrap modal

I need help with a Bootstrap modal in my project that has a close button positioned at the top right corner. I've used CSS to position the button, but it's not staying in one place consistently despite applying absolute positioning. I've tri ...

I've been attempting to relocate a CSS element at my command using a button, but my previous attempts using offset and onclick were unsuccessful

I am trying to dynamically move CSS items based on user input or button clicks. Specifically, I want to increment the position of elements by a specified number of pixels or a percentage of pixels. Currently, I am able to set the starting positions (top a ...

An unexpected error occurred in the Angular unit and integration tests, throwing off the script

I seem to be facing a recurring issue while running unit/integration tests for my Angular project using Karma. The tests have a 50:50 success/failure rate, working fine on my machine but failing consistently on our build server, making the process quite un ...

Guide on including the angular value (id) in conjunction with repeating data-target for executing a function

I have the following code snippet. Now, I am trying to pass a dynamic AngularJS variable, specifically the id of a repeating list. The button in question is used for deactivation purposes, and upon clicking it, a confirmation box pops up. Upon confirming ...

The definition of require is missing in the MEAN stack node

Currently experimenting with building an application on the MEAN stack and encountered a hurdle involving the use of Node's require function. Here is my current project structure: -- app -- images -- scripts -- app.js // configuration fi ...

The anchor tag seems to be malfunctioning within the div container

<style type="text/css> .xyz { position: absolute; top: 120px; left: 160px; z-index: -1; } #container { position: relative; overflow: visible; opacity: .3; } </style> <body> <div> <video i ...

Creating a VueJS Web App that is Distributable and Distributed

My challenge is to develop a distributable app using VueJS for four different companies, each with their own unique products database and custom settings. These companies want to integrate a page on their websites that displays their specific catalogue wit ...

When trying to pass 3 parameters from an Angular frontend to a C# MVC backend, I noticed that the server side was receiving null

I have encountered an issue where I am attempting to pass 3 parameters (2 types and one string) but they are showing up as null on the server side. Below is my service: const httpOptions = { headers: new HttpHeaders({ 'Content-Type&ap ...

Having various ng-apps within a single parent app

Exploring angularjs for the first time and experimenting with multiple ng-apps on a single page. For example, having app2 inside app1 and app1 within rootApp. controller1 includes an $http service that retrieves id and name values and assigns them to $roo ...

Upon loading the page, include a class to a specific element within an AngularJS ng-repeat function by evaluating the content of a JSON object

I have a group of buttons that are generated from a json object. Whenever a user clicks on a button, it changes color (referred to as the selected color) using the ng-class directive with bootstrap classes. If the same button is clicked again, it reverts b ...

The specified element type is not valid: only a string (for built-in components) or a class/function is expected when attempting to display a component

`Unhandled Runtime Error Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you mi ...

How can one quickly display a confirmation dialog box within react-admin?

Looking for a way to implement a confirmation dialog in my react-admin project, similar to JavaScript's alert function but more visually appealing. I want the user to only proceed with certain database operations if they click OK on the dialog. I cou ...

What will be provided as the outcome?

I have recently started learning express.js. The following code snippet is taken from the router library of express.js. var proto = module.exports = function(options) { options = options || {}; function router(req, res, next) { router.handle(req, ...

developing an associative object/map in JavaScript

I have a form featuring various groups of checkboxes and I am attempting to gather all the selected values into an array, then pass that data into an Ajax request. $('#accessoriesOptions input').each(function(index, value){ if($(this).prop(& ...

obtain the final result once the for loop has finished executing in Node.js and JavaScript

There is a function that returns an array of strings. async GetAllPermissonsByRoles(id) { let model: string[] = []; try { id.forEach(async (role) => { let permission = await RolePermissionModel.find({ roleId: role._id }) ...

Generate a list of files and transfer them to an input file

I am currently working on creating a drag and drop area where I can retrieve dataTransfer items using webkitGetAsEntry, and then differentiate between directories and files. My goal is to convert these files into a FileList and transfer them to a file inp ...