๐Ÿ’ป
B.TECH โ€ข SKILL DEVELOPMENT COURSE

Node JS / React JS / Django Lab

Web Development Laboratory โ€ข Experiment 8

๐Ÿ’ป Node JS โš›๏ธ React JS ๐ŸŒ Web Development ๐Ÿงช Lab Program
Experiment 08

Maintaining the transactional history of any user is very important. Explore the various session tracking mechanism (Cookies, HTTP Session).

โ† All Lab Programs
EXP-08

Step 1: Create an OpenWeatherMap Account and Generate API Key

Locate API key

image

Step 2: Set up a new React project


npxcreate-react-app weather-app


cd weather-app

Step 3: Install required packages

In the project directory, install the necessary packages by executing the following command


npm install axios

We will use the Axios library to make HTTP requests to the OpenWeatherMap API.

Step 4: Create a Weather component


import React, { useEffect, useState } from 'react';

import axios from 'axios';

const Weather = () => {
  const [city, setCity] = useState('');
  const [weatherData, setWeatherData] = useState(null);

  const fetchData = async () => {
    try {
      const apiKey = 'c97c0c1086d42990e89d64d76f50bb61'; // Replace with your OpenWeatherMap API key
      const response = await axios.get(
        'https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}'
      );
      setWeatherData(response.data);
      console.log(response.data); //You can see all the weather data in console log
    } catch (error) {
console.error(error);
    }
  };


useEffect(() => {
fetchData();
  }, []);

  const handleInputChange = (e) => {
    setCity(e.target.value);
  };

  const handleSubmit = (e) => {
e.preventDefault();
fetchData();
  };

  return (
<div>
<form onSubmit={handleSubmit}>
<input
          type="text"
          placeholder="Enter city name"
          value={city}
          onChange={handleInputChange}
        />
<button type="submit">Get Weather</button>
</form>
      {weatherData ? (
<>
<h2>{weatherData.name}</h2>
<p>Temperature: {weatherData.main.temp} C</p>
<p>Description: {weatherData.weather[0].description}</p>
<p>Feels like : {weatherData.main.feels_like} C</p>
<p>Humidity : {weatherData.main.humidity}%</p>
<p>Pressure : {weatherData.main.pressure}</p>
<p>Wind Speed : {weatherData.wind.speed}m/s</p>
</>
      ) : (
<p>Loading weather data...</p>
      )}
</div>
  );
};

export default Weather;

Replace {YOUR_API_KEY} in the API URL with the API key you generated from OpenWeatherMap.

Step 5: Connect the Weather component to your app.


import React from'react';

import Weather from'./Weather';

const App = () => {
return (
<div>
<h1>Weather Forecast App</h1>
<Weather />
</div>
  );
};

exportdefault App;

Your output should look like this:

Output :

Initial Screen

image

After Supply the City name

image
โ† Back to Lab Programs ๐Ÿ“š All Lab Manuals
```