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

Struggling to update the color of my SpeedDial component in MUI

I'm having trouble changing the color of my speed dial button. The makeStyle function has been working fine for everything else. Any suggestions? import React, {useContext} from 'react'; import {AppBar, Box, Button, Container, makeStyles, To ...

"Encountering an Issue with Storing Private Key as a String in NodeJS: Saving to .txt Results in Writing "[

Currently, I am attempting to save an EC key pair from the elliptic library as a string in a .txt file. However, when I do this, it ends up writing ""[object Object]"" to the file. UPDATE: Just wanted to note that the issue of turning the object ...

Merging the `on('click')` event with `$(this)`

Hello everyone, this is my first time posting here. I have a question regarding the possibility of achieving a specific functionality. I would like to attach click events to a series of anchor links and then use the $.get() method to reload some icons. T ...

Change Observable<String[]> into Observable<DataType[]>

I'm currently working with an API that provides me with an Array<string> of IDs when given an original ID (one to many relationship). My goal is to make individual HTTP requests for each of these IDs in order to retrieve the associated data from ...

Is there a way to verify the presence of data and halt code execution if it is not found?

In my data, there is a table containing a total of 5 links. The first 2 links can vary in availability as they are dynamic, while the last 3 links are static and are always displayed. The dynamic links' data is deeply nested within the state object, s ...

Nuxt-Gmap displaying multiple infowindows

Does anyone know how to close an info window if a user clicks on another marker? In the Google documentation, you open infowindows manually, but in nuxt-gmap it's like this: <GMap :key="mapRender" ref= ...

JQuery Ajax encounters a 500 error message due to an internal server issue

I'm currently using the jQuery library to send an ajax request to a PHP file. Initially, everything was working perfectly fine with a relative path like this: url:"fetch_term_grades.php", However, when I modified the path to be more specific like th ...

JavaScript Simplified Data Sorting after Reduction

I have extracted data from a JSON file and successfully condensed it to show the number of occurrences. Now, my next step is to arrange these occurrences in descending order, starting with the most frequent. To illustrate: var myData = [{ "datapo ...

Checking the alignment of a label or element in the center of a webpage using javascript

I am new to JavaScript and was attempting to determine if an element is centered aligned by accessing its CSS properties/values. Can someone help me retrieve the CSS property to verify text alignment using JavaScript? ...

A guide on incorporating oAuth 2.0 into Tizen

Currently, I am in the process of incorporating Google authentication using oAuth 2.0 in Tizen. I am following the guidelines provided here. Despite successfully obtaining the user code as instructed in the link, I keep receiving an invalid request error w ...

What is the best way to retrieve information from a local JSON file and store it in the state of

I am currently working on a project to develop a movies/series search app using Next.js and React based class components. I have successfully imported JSON content and displayed it using the map function as shown below: <div> {Appletv.shows.map(( ...

How can you attach a d3 graphic to a table that was created automatically?

Calling all experts in d3, I require urgent assistance!! On this web page, a JSON is fetched from the server containing 50 different arrays of numbers and related data such as 90th percentiles, averages, etc. A table is dynamically created with the basic ...

Node.js - Error: Undefined:0 SyntaxEncountered an unexpected end of input syntax error

Exploring Node.js and Backbone.js for the first time. Using the book "Backbone Blueprints" but encountering issues with the provided code to set up the webserver. Node.js is installed and running fine. Here's the package.json code: { "name": "simp ...

There seems to be a malfunction in the PHP controller causing issues with the functionality

Currently, I am utilizing jQuery and PHP for my project. In the controller, I have integrated AJAX functionality. Upon the initial click action, the result is successfully retrieved (the current "show more button" is hidden and a new "show more button" is ...

The concept of IFA on Android and accessing it through the browser/javascript

IFA (Identifier for Advertisers) is a new feature in iOS 6 that functions as a unique ID for tracking user context anonymously and improving the overall experience. My inquiries mainly focus on the realm of web development (specifically mobile browser/jav ...

Is it feasible to obtain multiple tag-name indexes using JavaScript?

Exploring the table search function provided by W3Schools has brought up an interesting question in my mind. Is it feasible to simultaneously retrieve multiple indexes using getElementsByTagName and conduct a search across the entire table instead of just ...

Making jQuery work: Utilizing tag replacements

My current code is: this.html(this.html().replace(/<\/?([i-z]+)[^>]*>/gi, function(match, tag) { return (tag === 'p') ? match : '<p>'; return (tag === '/p') ? match : '</p& ...

The socket.io-client could not be located on the running Node.js server

Setting up a fresh installation of Node, Express, and Socket.io on a Linux environment using npm. When attempting to run a sample from the official socket.io source, I encountered an error stating that the 'socket.io-client' module was not found ...

The issue arises when PhantomJS and Selenium fail to execute iframe JavaScripts while attempting to log in to Instagram

Currently utilizing Python alongside Selenium and PhantomJS, I encountered an issue while attempting to login to Instagram. It seems that PhantomJS is unable to process iframes' JavaScripts properly; interestingly, when trying the same action with Fir ...

Node.js - Retrieving POST request parameters and directing users in an Express application

I encountered this specific issue while setting up a post endpoint for my nodejs CLI script that utilizes express to handle requests. app.use( express.static( path.format({dir: __dirname, base: 'client/dist'})) ); app.use( express ...