I am facing an issue where the weather information is not being displayed even after sending a request to

I'm working on building an app that will provide users with weather data once they input a city. Utilizing the openweathermap.org API for this purpose, I've noticed in my console under networks that an API call is made when the city is entered, but no data is being returned. The missing data should include the city name, temperature, and weather conditions. Any suggestions on how to troubleshoot and fix this issue would be greatly appreciated.

App.js:

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

function App() {
  const apiKey = 'API Key'; //Added my personal 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=${city}&units=imperil&APPID=${apiKey}` //Copied this API snippet 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 the weather app! Enter the city you wish to check the weather of.</p>
        </div>
      ) : (
        <div className="weather-data">
          <p className="city">{weatherData.name}</p>
          <p className="temp">{Math.round(weatherData.main.temp)}℉</p>
          <p className="weather">{weatherData.weather[0].main}</p>
        </div>
      )}

      {weatherData.cod === '404' ? <p>City not found.</p> : <></>}
    </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;
 }

 .weather-data{
  margin-top: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
 }

 .city{
  font-size: 30px;
  font-weight: 200;
 }

 .temp{
  font-size: 90px;
  padding: 10px;
  border: 1px solid lightgray;
  border-radius: 12px;
 }

 .weather{
  font-size: 30px;
  font-weight: 200;
 }

Answer №1

When using the fetch function, make sure to input a regular string as a parameter.

Replace the single straight tick with backticks (`) and enclose variables within ${} to convert them into strings.

Answer №2

Did you spot the mistake? The "s" should actually be a $

https://api.openweathermap.org/data/2.5/weather?q=s{city}&units=imperil&APPID=${apiKey}



https://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperil&APPID=${apiKey}

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

Ways to clear all CSS rules from a class without deleting the class itself using jQuery

Clear out all CSS properties within a class without actually removing the class itself using jQuery For instance : .ui-widget { font-family: Verdana, Arial, sans-serif/*{ffDefault}*/; font-size: 1.1em/*{fsDefault}*/; left: 350 ...

Expanding a JavaScript list using HTML inputs

I have a script where a grid dynamically displays a list of words. Is there a way to populate the word list in the grid using HTML? Currently, I am doing this... var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog"]; Can additional words be adde ...

Issue with parsley customized error message functionality not functioning as expected

I'm currently dealing with an issue related to the input field below: <input id="name" name="real_name" type="text" placeholder="ie. Your full name or company name" class="form-control input-lg parsley-validated" data-required="true" parsley-er ...

The appearance of Bootstrap React Nextjs doesn't quite match what's shown in the documentation

I am developing the frontend of my application using a combination of bootstrap, react, and nextjs. I attempted to implement the example provided by react-bootstrap at https://codesandbox.io/s/github/react-bootstrap/code-sandbox-examples/tree/master/basic. ...

Is there a method available that would allow me to display my HTML code within a frame using Selenium WebDriver and Java?

Currently, I am in the process of automating an Application that includes several embedded iframes. I am wondering if there is a method to view my HTML source code within these frames. ...

Mobile responsiveness malfunctioning

I recently launched my first responsive design website, which you can view here After testing the responsiveness on Chrome and FF by resizing the window, everything seemed to be working fine. However, when I checked it on my phone, the layout appeared ide ...

How come the subitems of a second-level nested list do not appear when hovering over a hyperlink?

Show "News" in French when hovering over the French option. ul#topmenu li a#HyperLink:hover ul { background-color: pink; display: list-item; } <ul id="topmenu"> <li class="langHorzMenu"> <a href="#" id="HyperLink">French</ ...

Is it possible to load the surrounding markup in Angular before the guards are resolved upon the initial load of the router-outlet?

Within our Angular 12 application, we have implemented guards that conduct checks through API calls to the backend in order to validate the user's permissions for accessing the requested route. The default behavior of these guards follows an all-or-no ...

Tips for iterating through an array of images and displaying them in a React component

I am working on a project in my react app where I have 5 images that I want to cycle through indefinitely. The goal is to create an animation where a light bar appears to be constantly moving. The shifting dot in each image will give the illusion of movem ...

Can you please share the updated method for defining the traditional `inline-block` display setting?

Recently, CSS has undergone a change where the display property is now split into an inner display and outer display. With the legacy value of display: inline-block, it raises the question of what the newer equivalent should be. One might assume that the ...

Removing background color and opacity with JavaScript

Is there a way to eliminate the background-color and opacity attributes using JavaScript exclusively (without relying on jQuery)? I attempted the following: document.getElementById('darkOverlay').style.removeProperty("background-color"); docume ...

I am having trouble with the functionality of my bootstrap navbar toggler

Can you please review the code and help me identify the issue? The toggle button is not functioning properly, it should display the menu bar when clicked. <body> <!--navigation bar--> <nav class="navbar navbar-expand-sm navbar-dark bg-dan ...

material-ui DropDown with an image displayed for the selected value

Can someone help me figure out how to display an image in my material-ui dropdown menu? I'm currently using version 0.19.1 and have written the following code: <DropDownMenu autoWidth style={{ width: 500, marginBottom: 30 }} underlin ...

New Authentication: The sign-in feature will redirect to /api/auth/error

Currently implementing Google sign-in functionality on my Next.js 13 app using Next-auth. I have utilized the signIn() function as described in the documentation here. However, upon calling the signIn() function, I am unexpectedly redirected to http://loca ...

Designing Buttons and Titles for the Login Page

I'm currently working on developing a straightforward login page in react native and I've encountered some difficulties with styling. Does anyone have tips on how to center the text on the button? Also, is there a way to move the INSTARIDE text ...

During the deployment process on Firebase, an error message appeared stating, "The specified file could not be found on this website. Please review the URL for any errors and attempt again."

Currently, I am in the process of deploying a React project with Firebase. The path I am using is as follows: <Route exact path="/product-type/laptop" element={<Allproductpage type={'Laptop'} />} /> While this setup is fun ...

The term "Cardlist" has not been defined and is therefore causing an

I created a CardList and attempted to add cards into the list using map, but encountered an error import React from 'react'; import Card from './Card'; const CardsContainer = ({robots}) => { const cardComponents = robots.map((r ...

What is the best way to display or hide specific tables depending on the button chosen?

Being fairly new to JavaScript, I find myself unsure of my actions in this realm. I've successfully implemented functionality for three links that toggle visibility between different tables. However, my ideal scenario would involve clicking one link t ...

Incorporate several websites into a React application without using iframes

After developing a React application with create-react-app, I attempted to embed another website onto the app using an iframe. Everything worked perfectly until I wanted to resize the iframe to fit the page, resulting in a Blocked a frame with origin from ...

Interact seamlessly using GraphQL clients with React

Is it advisable to utilize React in conjunction with GraphQL clients such as Apollo Client? Can I achieve similar outcomes using react and the new Context API? In essence, I could interact with GraphQL APIs by employing axios or similar libraries. Moreove ...