OpenWeatherMap API call failing - not visible in Network tab of Console

I am facing an issue with my API call while trying to retrieve temperature data for a specific city. I am unsure if the problem lies with my API key or the code itself. Can you please provide guidance on how I can resolve this issue? Upon entering the city name in the web app and pressing enter, the API call does not appear in the network settings of my console.

App.js:

import React, { useState } from 'react';
import './App.css';

function App() {
  const apiKey = 'API KEY'; //I added my API key here
  const [weatherData, setWeatherData] = useState([{}]);
  const [city, setCity] = useState('');

  const getWeather = (event) => {
    if (event.key == 'ENter') {
      fetch(
        'https://api.openweathermap.org/data/2.5/weather?q=s{city}&units=imperil&APPID=${apiKey}' //this API was taken from a tutorial
      )
        .then((response) => response.json())
        .then((data) => {
          setWeatherData(data);
          setCity('');
        });
    }
  };
  return (
    <div className="container">
      <input
        className="input"
        placeholder="Enter City..."
        onChange={(e) => setCity(e.target.value)}
        value={city}
        onKeyPress={getWeather}
      />

      {typeof weatherData.main === 'undefined' ? (
        <div>
          <p>
            {' '}
            Welcome to weather app! Enter the city you want the weather of.
          </p>
        </div>
      ) : (
        <div>
          <p>{weatherData.name}</p>
          <p>{Math.round(weatherData.main.temp)}℉</p>
          <p>{weatherData.weather[0].main}</p>
        </div>
      )}
    </div>
  );
}

export default App;

App.css:

.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 25px;
 }

 .input {
padding: 15px;
width: 80%;
margin: auto;
border: 1px solid lightgrey;
border-radius: 6px;
font-size: 16px;
 }

 .input:focus{
  outline: none;
 }

Answer №1

Looks like a small mistake in your code

It needs to be corrected to

if (event.key == 'Enter') 

inside the fetchData function

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

Example TypeScript code: Use the following function in Angular 5 to calculate the total by summing up the subtotals. This function multiplies the price by the quantity

I have a table shown in the image. I am looking to create a function that calculates price* quantity = subtotal for each row, and then sum up all the subtotals to get the total amount with Total=Sum(Subtotal). https://i.stack.imgur.com/4JjfL.png This is ...

How can I update the value of one select tag when another select tag is changed?

My web page contains two select options as shown below. https://i.sstatic.net/kmDv3.jpg There are two select options labeled as #age1 and #age2, with age values ranging from 18 to 30. I want to ensure that when a user selects an age from #age1, the minim ...

Mathematics - Determined the dimensions of an adjusted image size

Currently, I am implementing a basic mathematical method to crop an image. My approach involves utilizing the jQuery plugin called imageareaselect.js to overlay an adjustable layer on top of an image. By resizing this layer with the cursor and clicking a b ...

Creating a React Component in TypeScript that utilizes Promise Objects for data handling

After receiving a Promise type Object as a response, an error has been encountered: Error: Objects are not valid as a React child (found: object with keys { key1, key2, key3 ...}... How can this issue be resolved? // Component.tsx import React, { us ...

Separating the rules for development and production modes in the webpack configuration file

I'm currently in the process of working on a front-end project using HTML. Within my project, I have integrated the Webpack module bundler and am utilizing the image-webpack-loader package for image optimization. However, I've encountered an issu ...

Accessing the state array in React is vital for manipulating and displaying

Is there a way to update the state of my array order conditionally, checking for duplicates, without being able to access order values inside the function addToBasket? It seems like the console.log shows that it's updated and accessible in one instanc ...

Does React component re-render cause variables declared outside to reset?

My React code snippet looks like this: let hasInitialRendered = true function App(props){... hasInitialRendered = false; ... } If the App component is re-rendered (by changing its props or state), will the hasInitialRendered variable be reset to true? ...

The form within the while loop is only functioning with the initial result

Within a while loop, I have a form that is being processed with ajax. The issue is that it only works on the first form and not on the others. Can someone take a look? <?php while($a = $stmt->fetch()){ ?> <form method="post" action=""> ...

The border of the cell in the top row only partially overlaps with the margin area

Have you noticed how the left border of the first cell doesn't line up with the margin area of the table? This peculiar phenomenon seems to occur only in the first row: https://i.stack.imgur.com/qMWCh.jpg In all other rows, the border aligns proper ...

Using the Bootstrap class `d-flex align-items-center` will shift items slightly off-center towards the left side

As I delved into a web development course led by Andrei Neagoie, everything was smooth sailing and I was thoroughly enjoying the material. However, when I reached the section on Bootstrap (where Andrei was constructing a startup landing page), I encountere ...

Is there a way to extract all the `<select>` elements from a table and store them in an array?

I'm having some trouble with the order of my code and the array output. Everything seems to be a bit jumbled up right now and I can't figure out how to add all the rows correctly. $('#clicker').on('click', function(e) { v ...

Arranging information within an ExpansionPanelSummary component in React Material-UI

https://i.stack.imgur.com/J0UyZ.png It seems pretty clear from the image provided. I've got two ExpansionPanelSummary components and I want to shift the icons in the first one to the right, next to ExpandMoreIcon. I've been playing around with C ...

What is the correct way to implement checkbox validations using jQuery?

I have a total of 3 checkboxes that I would like to arrange in a particular order based on their checks. Currently, when one checkbox is selected for download, the logic I have implemented only considers the first checkbox and ignores the rest. I am look ...

A challenge in web design: tackling cross-browser color discrepancies

I have implemented CSS code in an HTML page to define the color values of H1 and H2 elements. <style type="text/css"> img {border-style: none;} H1 {color: "#33CCFF"} H2 {color: "#33CCFF"} </style> While this setup works well on Internet Explo ...

Changing the Background Color of the Toolbar in Ionic

I am having trouble making the background color of my footer dynamic. I have tried binding the element to a class or applying dynamic styling, but it doesn't seem to work. Even when I have this in my HTML: <ion-footer align="center" style="height: ...

Guide for using JavaScript to obtain the current line position within a contenteditable div during a keypress event

I am in the process of developing a customized editor using a contenteditable div. I require a javascript code that can determine the line position of the current caret position during a keypress event. It should be able to adapt when new lines are added o ...

Discover the art of implementing linear gradient backgrounds in Tailwind css effortlessly

Is there a way to incorporate this specific color scheme into my background? linear-gradient(355.45deg, #FFFFFF 11.26%, rgba(255, 255, 255, 0) 95.74%) I have knowledge on how to implement this color using regular CSS, but I'm curious about how it can ...

Two objects precisely located in the same spot yet not visible simultaneously

There are two elements here. One is a transparent button, and the other is an image positioned behind it. The background property didn't work for me, so I attempted different variations without success: .top-container > button { background-ima ...

issue with accessing the code through the web browser

Currently, I am developing a web application using ASP.NET MVC5. I have been coding and pushing my work to GitHub. However, I recently encountered an issue where I can no longer view my application on the browser. The "View in browser" option has disappear ...

Error message indicating that the function 'slice' is not defined for the data variable

I've already searched for solutions to a similar issue, but none of them worked for me. I'm dealing with an object that fetches a list of cities including their names, populations, and states. Here is my HTTP service request: cidadesUrl = 'h ...