[go: up one dir, main page]

0% found this document useful (0 votes)
8 views50 pages

NM Main Report Harish PDF

Uploaded by

DJ Gamer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views50 pages

NM Main Report Harish PDF

Uploaded by

DJ Gamer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

CHAPTER 1

INTRODUCTION

The Weather API React Web Application project aims to provide a user-
friendly platform that delivers accurate and real-time weather information. Using
React, a powerful front-end JavaScript library, this application interacts with
public weather APIs to fetch and display weather data for different locations. This
project is designed to be scalable, responsive, and feature-rich, offering users an
intuitive interface to explore weather conditions effortlessly.

The application focuses on core functionalities such as searching for


weather information by city name, retrieving location-based weather data using
geolocation, and displaying a detailed forecast, including temperature, humidity,
and other meteorological parameters. Advanced features such as trend
visualization using charts and state management through Redux enhance usability
and performance. Deployment on platforms like Vercel or Netlify ensures
accessibility and efficiency.

This documentation outlines the step-by-step process of building the


application, covering topics such as setting up the development environment,
understanding weather APIs, fetching data, creating reusable components, and
deploying the final product. By following this guide, developers can create a
robust weather application while mastering essential concepts in React
development and API integration.

1.1 Overview of Weather Applications

Weather applications are integral tools in modern life, offering crucial


information to users for daily planning and safety. These apps provide

1
meteorological data like temperature, humidity, wind speed, and precipitation
forecasts. With advancements in technology, they have become accessible to
global audiences through web and mobile platforms.

Weather apps leverage APIs to access real-time and historical weather data.
They cater to various use cases, such as helping individuals plan their travel,
aiding farmers with crop decisions, or informing businesses of weather-
dependent activities. This project aims to create such an application, highlighting
React’s strengths in building interactive user interfaces and robust data handling.

Additionally, the project illustrates how weather applications have


expanded functionalities, including personalized notifications, detailed forecasts,
and visual data representations. These enhancements make the application not
only practical but also user-friendly and engaging.

1.2Features and Use

Real-time Weather Updates: Users can instantly retrieve the current weather
conditions for any specified location.

Forecast Information: The app provides predictions for upcoming days, aiding
long-term planning.

Global Accessibility: Users can input any city worldwide and access weather
data, ensuring a versatile user experience.

Visual Elements: Data like temperature trends and weather conditions are
displayed with icons and charts for better understanding.

Use Cases:

Travel Planning: Travelers can plan their trips by checking weather forecasts for
their destinations.

2
Event Management: Organizers can choose dates and venues based on predicted
weather conditions.

Outdoor Activities: Enthusiasts can plan activities like hiking or sports events
with real-time updates.

Emergency Preparedness: Early warnings for adverse weather conditions, such


as storms, help in disaster management.

3
CHAPTER 2

SETTING UP THE DEVELOPMENT ENVIRONMENT

2.1 Installing Node.js and npm

Node.js is a critical runtime environment for executing JavaScript code


outside a browser, while npm (Node Package Manager) handles package
installation and dependency management. Setting up Node.js and npm is a
prerequisite for React development.

Steps to Install Node.js:

1. Visit the Node.js official website.

2. Download the LTS (Long-Term Support) version for stability.

3. Install Node.js by following the setup wizard.

4. Verify installation:

node -v

npm -v

These commands confirm that Node.js and npm are correctly installed.

npm simplifies the management of project dependencies, ensuring compatibility


and updates. For example, it facilitates installing essential libraries like Axios and
React Router.

It also allows scripts like npm start to streamline development processes.

4
2.2 Setting Up React Project with Create-React-App

Create-React-App (CRA) is a tool that helps developers set up a React


project with minimal configuration. By initializing the project using CRA,
developers save time and focus on application logic.

Steps to Initialize a React Project:

1. Run the command:

npx create-react-app weather-app

2. Navigate to the project directory:

cd weather-app

3. Start the development server:

npm start

CRA pre-configures a development environment with Webpack, Babel, and


ESLint. It also organizes the project into a clear folder structure:

src: Contains the application’s core logic.

public: Includes static assets.

node_modules: Houses installed dependencies.

2.3Installing Required Packages

React applications often require third-party libraries for specific functionalities.


Key packages for this project include:

Axios: A promise-based HTTP client for making API requests.

Install using npm install axios.

5
React Router: Enables routing within the application, allowing navigation
between different views.

Install using npm install react-router-dom.

Styling Libraries: Material-UI or Bootstrap for responsive and aesthetic designs.

Charting Libraries: Chart.js or Recharts for visualizing weather trends.

These tools ensure the application is feature-rich and visually appealing.

6
CHAPTER 3

UNDERSTANDING WEATHER APIs

3.1 Introduction to Weather APIs

Weather APIs provide programmatic access to weather data, enabling


developers to create applications that retrieve and display meteorological
information. Popular APIs include OpenWeatherMap and WeatherStack.

Key Benefits:

Access to real-time and historical data.

Easy integration through RESTful endpoints.

Support for global locations and advanced features like air quality metrics.

This project utilizes a weather API to fetch data like temperature, humidity, wind
speed, and forecasts. Developers must understand API endpoints, request
parameters, and response formats to ensure seamless integration.

3.2Obtaining an API Key

API keys authenticate requests, ensuring secure and controlled access to services.
Steps to obtain an API key:

Register on the chosen API’s website (e.g., OpenWeatherMap).

Generate a key from the dashboard.

Use the key in API requests as a query parameter:

https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_A
PI_KEY

7
API providers often set usage limits, so developers must optimize API calls to
avoid exceeding quotas.

3.3Exploring API Endpoints and Responses

Weather APIs offer multiple endpoints for varied functionalities:

Current Weather Data: Provides real-time data for a specified location.

Forecast Data: Returns weather predictions for multiple days.

Air Quality Index (Optional): Gives data on pollutants and air quality.

Responses are generally in JSON format, containing fields like temp, humidity,
and weather. Parsing this data is crucial for presenting it effectively in the
application.

8
CHAPTER 4

CREATING THE BASIC APPLICATION STRUCTURE

4.1Designing the Folder Structure

A well-organized folder structure is essential for scalability and maintainability.


Common folders include:

src/components: For reusable components like headers and search bars.

src/pages: For full-page components, such as Home or WeatherDetails.

src/services: For API-related logic, ensuring separation of concerns.

This approach simplifies navigation and future development.

4.2Creating Reusable Components

Reusable components like WeatherCard, SearchBar, or ForecastChart reduce


duplication and promote consistency.

Advantages:

Enhances code readability.

Simplifies updates or styling changes.

Components should receive props for flexibility and avoid hardcoding data.

4.3 Setting Up Routes

React Router manages navigation in single-page applications. Configure routes


as follows:

1. Install React Router:

npm install react-router-dom

9
2. Define routes in App.js:

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

<Router>

<Routes>

<Route path="/" element={<Home />} />

<Route path="/weather" element={<WeatherDetails />} />

</Routes>

</Router>

This enables seamless navigation between views.

10
CHAPTER 5

FETCHING WEATHER DATA

5.1 Using Axios to Fetch Data

Axios is a promise-based HTTP client that simplifies fetching data from


APIs. It is a powerful tool for making asynchronous requests and handling
responses efficiently in JavaScript applications. This project uses Axios to
interact with the weather API and retrieve real-time weather data for different
locations.

Steps to Use Axios in a React Project:

1. Installation: Install Axios using npm:

npm install axios

2. Importing Axios: Import it into your component:

import axios from 'axios';

3. Making API Requests: Use the axios.get method to fetch data from the
weather API:

const fetchData = async () => { try {

const response = await


axios.get('https://api.openweathermap.org/data/2.5/weather?q=London&appi
d=YOUR_API_KEY');

console.log(response.data);

} catch (error) {

console.error('Error fetching data:', error); } };

11
4. Handling Asynchronous Responses: Use async/await or .then() for handling
asynchronous calls effectively.

Key Features of Axios:

Simplifies HTTP requests.

Automatically parses JSON responses.

Built-in error handling mechanisms.

Supports request/response interceptors for pre/post-processing.

Axios enables seamless communication with the weather API, ensuring efficient
data retrieval for the application.

5.2 Handling API Errors and Edge Cases

Handling errors and edge cases is crucial for providing a robust user
experience. APIs may fail due to network issues, incorrect API keys, or exceeding
usage limits.

Common Error Scenarios:

Invalid API Key: Ensure the API key is valid and properly included in the
request.

Network Issues: Handle connectivity issues gracefully by displaying appropriate


messages.

Rate Limits: Implement mechanisms to monitor API usage and avoid exceeding
limits.

Invalid Input: Validate user input before making API requests.

12
Error Handling Techniques:

Use try-catch blocks to capture errors:

try {

const response = await axios.get(API_URL);

} catch (error) {

console.error('Error:', error);

Display error messages to inform users about issues:

setError('Failed to fetch data. Please try again.');

Implement fallback UI components, like placeholders or default messages.

By anticipating potential errors, developers can ensure the application remains


functional under various conditions.

5.3 Parsing API Response for Display

API responses are usually in JSON format, requiring data extraction and
transformation for display in the UI.

Steps to Parse Data:

Inspect the API Response: Analyze the structure using browser developer tools
or console.log(response.data).

Extract Relevant Fields: Use destructuring to access specific data:

const { temp, humidity } = response.data.main;

const { description } = response.data.weather[0];

Format Data: Transform the raw data for better readability:

13
Convert temperature from Kelvin to Celsius:

const celsius = temp - 273.15;

Format dates or times using libraries like moment.js or date-fns.

Pass Data to Components: Use props to pass parsed data to UI components for
rendering:

<WeatherCard temp={celsius} description={description} />

Parsing ensures that raw API data is translated into user-friendly information,
enhancing the application's usability.

14
CHAPTER 6

BUILDING THE USER INTERFACE

6.1 Creating a Search Bar Component

The search bar is a critical feature, allowing users to input city names and
fetch weather data. This reusable component enhances interactivity and usability.

Steps to Build the Search Bar:

1. Component Setup: Create a new functional component:

const SearchBar = ({ onSearch }) => {

const [query, setQuery] = useState('');

const handleSearch = () => {

if (query) onSearch(query);

};

return (

<div>

<input

type="text"

value={query}

onChange={(e) => setQuery(e.target.value)}

placeholder="Enter city name”/>

<button onClick={handleSearch}>Search</button>

</div>

15
);};

export default SearchBar;

State Management: Use useState to manage user input.

Event Handling: Capture input changes and trigger the onSearch function when
the button is clicked.

6.2 Displaying Weather Information (Temperature, Humidity, etc.)

Displaying fetched weather data involves presenting key metrics like


temperature, humidity, and weather conditions in an intuitive format.

Steps to Display Data:

Create a Weather Display Component:

const WeatherDisplay = ({ temp, humidity, description }) => {

return (

<div>

<h2>Current Weather</h2>

<p>Temperature: {temp} °C</p>

<p>Humidity: {humidity}%</p>

<p>Condition: {description}</p>

</div>

);

};

export default WeatherDisplay;

16
Pass Data via Props: Ensure the component receives parsed weather data.

Styling: Use CSS or Material-UI to format the layout and add icons for visual
appeal.

Displaying weather information effectively ensures the application’s core


functionality is delivered to users.

6.3 Styling the Application with CSS/Material-UI

Styling transforms the application's UI, improving user experience and visual
appeal.

Styling Techniques:

CSS Modules: Scope styles locally to prevent conflicts:

/* WeatherCard.module.css */

.card {

background: #f0f8ff;

padding: 20px;

border-radius: 8px;

Material-UI: Use pre-built components for responsive and consistent designs

import { Card, CardContent, Typography } from '@mui/material';

const WeatherCard = ({ temp, description }) => (

<Card>

<CardContent>

<Typography variant="h5">{temp} °C</Typography>

17
<Typography>{description}</Typography>

</CardContent>

</Card>

);

Responsive Design: Use CSS Flexbox/Grid or Material-UI’s Grid component


to ensure layouts adjust to screen sizes.

Styling ensures the application is not only functional but also aesthetically
pleasing and accessible across devices.

18
CHAPTER 7

IMPLEMENTING ADVANCED FEATURES

7.1 Adding Location-Based Weather (Geolocation API)

Location-based weather functionality allows the application to fetch and


display weather information based on the user’s current geographic location.
This is achieved using the Geolocation API available in modern web browsers.

Steps to Implement Location-Based Weather:

Accessing the Geolocation API:

Use the navigator.geolocation object to fetch the user’s coordinates:

navigator.geolocation.getCurrentPosition(position) =>

const { latitude, longitude } = position.coords;

console.log(latitude, longitude);

},

(error) => {

console.error('Error fetching location:', error);

});

Fetching Weather Data: Pass the latitude and longitude to the weather API:

const fetchWeatherByLocation = async (lat, lon) => {

try {

const response = await axios.get(`https://

19
api.openweathermap.org/data/2.5/weather?lat=

${lat}&lon=${lon}&appid=YOUR_API_KEY`);

console.log(response.data);

} catch (error) {

console.error('Error fetching weather data:', error) }}

Error Handling: Handle scenarios where location access is denied or


unavailable, and provide a fallback.

Enhancing UX: Display a loading spinner while fetching location and weather
data.

Benefits of Location-Based Weather:

• Improves user experience by automatically providing relevant weather data.

• Reduces the need for manual input.

7.2 Displaying Forecast for Multiple Days

Multi-day forecasts offer users a broader view of upcoming weather conditions,


enhancing the application's utility.

Steps to Implement Multi-Day Forecast:

1. Explore the API Endpoint: Identify the appropriate endpoint, such as


forecast from OpenWeatherMap.

const fetchForecast = async (city) => {

try {

const response = await


axios.get(`https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=
YOUR_API_KEY`);

20
console.log(response.data);

} catch (error) {

console.error('Error fetching forecast:', error);

};

Parse and Group Data: Extract data points for specific times (e.g., 12 PM
daily):

const dailyData = forecastData.list.filter(item =>


item.dt_txt.includes('12:00:00'));

Design Forecast Cards: Create reusable components to display the forecast for
each day:

const ForecastCard = ({ date, temp, description }) => (

<div>

<h4>{date}</h4>

<p>{temp} °C</p>

<p>{description}</p>

</div>);

Integrate into UI: Map the forecast data into ForecastCard components and
display them in a grid.

Styling: Use CSS/Material-UI to format and add icons for weather conditions.

Multi-day forecasts provide users with actionable insights for planning their
activities.

21
7.3 Adding Graphs/Charts for Weather Trends

Graphs and charts visually represent weather trends, such as temperature


variations over time, offering users an intuitive understanding.

Steps to Add Graphs/Charts:

Choose a Charting Library: Use libraries like Chart.js or Recharts:

npm install chart.js

Integrate the Library: Create a chart component:

import { Line } from 'react-chartjs-2';

const TemperatureChart = ({ data }) => {

const chartData = {

labels: data.map(item => item.time),

datasets: [

label: 'Temperature (°C)',

data: data.map(item => item.temp),

borderColor: 'blue',

fill: false,

},

],

};

return <Line data={chartData} />;

};

22
export default TemperatureChart;

Prepare Data: Format API response data for the chart:

const formattedData = forecastData.map(item => ({

time: item.dt_txt,

temp: item.main.temp - 273.15,

}));

1. Add to UI: Embed the chart component in the forecast section.

2. Customization: Adjust styles, colors, and legends for clarity.

Graphs and charts elevate the application's professionalism and user


engagement.

23
CHAPTER 8

STATE MANAGEMENT

8.1 Using React Hooks for State Management

React Hooks like useState and useEffect enable efficient state


management in functional components.

Common Use Cases:

• Manage input fields, such as the search query.

• Store fetched weather data.

• Track loading and error states.

Example:

const [weatherData, setWeatherData] = useState(null);

useEffect(() => {

fetchWeather();

}, []);

React Hooks simplify state management without requiring external libraries.

8.2 Global State Management with Redux

Redux centralizes application state, making it accessible across components.

Steps to Set Up Redux:

1. Install Redux and React-Redux:

npm install redux react-redux

2. Create a Redux store:

24
import { createStore } from 'redux';

const store = createStore(rootReducer);

3. Define actions and reducers for weather data.

4. Use the Provider component to wrap the application and connect


components with useSelector and useDispatch hooks.

8.3 Persisting Data with LocalStorage

LocalStorage retains user preferences and recent searches across sessions.

Steps to Use LocalStorage:

Save data:

localStorage.setItem('recentSearch', JSON.stringify(data));

Retrieve data:

const recentSearch = JSON.parse(localStorage.getItem('recentSearch'));

Persisting data improves the user experience by remembering past interactions.

25
CHAPTER 9

ENHANCING USER EXPERIENCE

9.1 Implementing Loading Indicators

Objective: Implementing loading indicators helps in informing users that the


system is processing their request, ensuring that they do not feel the application
is unresponsive.

Implementation:

UI Approach: Use loading spinners, progress bars, or skeleton screens to


indicate that the application is processing requests or fetching data.

React Implementation:

Utilize useState to manage loading states.

Use a conditional rendering method to show the loading indicator while data is
being fetched or processed.

Best Practices:

Keep loading times minimal and informative.

Allow users to continue interacting with other parts of the app if possible while
data is loading.

Customize loading indicators to match the app’s theme and design style.

9.2 Adding Error Messages for API Failures

Objective: To inform users of any issues during data fetching or API


interaction, such as network failures or server errors.

Implementation:

26
UI Approach: Display a user-friendly error message when the API call fails.
This could be a simple text message or an alert box depending on the severity of
the issue.

React Implementation:

Handle API failures using try-catch blocks or catch on promises.

Display error messages dynamically based on the error response.

Best Practices:

Ensure that error messages are clear and actionable (e.g., "Please check your
internet connection").

Avoid technical jargon; keep it user-friendly.

Consider logging the error for debugging and tracking.

9.3 Making the Application Responsive

Objective: Ensuring the app is usable on various devices and screen sizes,
providing a consistent experience for users across mobile, tablet, and desktop.

Implementation:

Responsive Design Principles: Use flexible layouts, media queries, and relative
units (percentages, em, rem) to ensure that the app scales across different screen
sizes.

React Implementation:

Utilize CSS frameworks like Bootstrap or Material-UI, which provide pre-built


responsive components.

Write custom media queries for tailored layouts.

27
Best Practices:

Test on multiple devices to ensure layout consistency.

Implement mobile-first design, meaning designs should be optimized for


smaller screens first.

Make navigation intuitive on smaller screens, perhaps incorporating a


hamburger menu or collapsible elements.

28
CHAPTER 10

DEPLOYMENT AND MAINTENANCE

10.1 Preparing the App for Deployment

Objective: Preparing the application for deployment involves optimizing the


build for production, ensuring the app is stable, and free of errors.

Steps for Preparation:

Optimize Assets: Minimize and bundle CSS and JavaScript files to reduce load
times.

Error Handling: Ensure all errors are handled properly to avoid crashes in
production.

Build Process: Run npm run build or equivalent to generate the production
build.

Code Cleanup: Remove unnecessary code, comments, and dependencies to


improve performance.

Best Practices:

Use environment variables for configuration to ensure flexibility between


development and production environments.

Test the production build thoroughly before deploying.

10.2 Deploying on Platforms like Vercel/Netlify

Objective: Deploy the app to a cloud platform, ensuring that it is accessible to


users over the internet.

29
Steps for Deployment:

Vercel:

Connect your Git repository to Vercel.

Configure environment variables on Vercel’s dashboard.

Deploy by pushing to the main branch or by linking the Git repository.

Vercel automatically builds and deploys the app with every push to the
connected branch.

Netlify:

Connect your Git repository to Netlify.

Configure the build settings (e.g., npm run build).

Set up environment variables and deploy.

Best Practices:

Use continuous deployment (CD) to automate deployments.

Set up proper DNS configurations for custom domains.

Monitor deployment logs for any potential issues.

30
APPENDIX

SOURCE CODE

React Weather Web Application Project Structure:

1) Node Modules (Folder)

2) src (Folder)

1. assets (Folder)

a) cloudy-weather.png

b) drizzle.png

c) humidity.png

d) rain.png

e) search.png

f) snow.png

g) sun

h) weather-app.png

i)weatherhome.png

j)wind.png

3) app.css

4) app.js

5) main.jsx

6) index.html

7) package-lock.json

31
8) package.json

1) app.css

*{

padding: 0;

margin: 0;

box-sizing: border-box;

font-family: sans-serif;

.main {

background: url('../src/assets/weatherHome.jpg') no-repeat center center;

background-size: cover;

height: 100vh;

width: 100%;

display: flex;

align-items: center;

justify-content: center;

.container {

width: 350px;

background-color: white;

border: 1px solid;

32
height: auto;

border-radius: 10px;

box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);

padding: 10px;

.search {

height: auto;

padding: 10px;

display: flex;

justify-content: center;

border: 2px solid skyblue;

border-radius: 5px;

width: 90%;

margin: 10px auto;

.search input {

width: 95%;

border: none;

background-color: white;

outline: none;

.img-search {

33
height: 20px;

width: 20px;

cursor: pointer;

.image {

text-align: center;

height: 100px;

margin: 20px 0px;

.image img {

height: 80px;

width: 80px;

.temper,.city,.country {

font-size: 35px;

text-align: center;

margin-top: 10px;

text-transform: uppercase;

.temper {

font-size: 25px;

font-weight: bold;

34
}

.city {

color: orange;

.country {

font-size: 15px;

color: #888;

font-weight: 500;

.cord {

display: flex;

justify-content: center;

gap: 30px;

margin-top: 20px;

padding: 10px;

.cord div {

display: flex;

flex-direction: column;

gap: 5px;

align-items: center;

35
.cord2 {

display: flex;

justify-content: space-between;

margin-top: 10px;

padding: 20px;

.cord2 div {

display: flex;

flex-direction: column;

gap: 5px;

align-items: center;

.humidity-icon{

height: 25px;

width: 25px;

.wind-icon{

height: 25px;

width: 50px;

.designed{

text-align: center;

36
font-size: 10px;

.designed span{

color: orangered;

font-size: 10px;

font-family: 'Segoe UI';

font-style: italic;

font-weight: bold;

.loading{

text-align: center;

margin: 15px;

.citynot{

text-align: center;

font-family: cursive;

font-weight: bolder;

font-size: 30px;

margin: 15px;

background-color: red;

padding: 10px;

border-radius: 5px;

37
color: white;

border: 2px solid black;

2)app.jsx

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

import './App.css'

import SunIcon from './assets/sun.svg'

import SearchIcon from './assets/search.svg'

import HumidityIcon from './assets/humidity.svg'

import WindIcon from './assets/wind.svg'

import CloudWeatherIcon from './assets/cloudy-weather.svg'

import DrizzleIcon from './assets/drizzle.svg'

import RainIcon from './assets/rain.svg'

import SnowIcon from './assets/snow.svg'

const WeatherDetails = ({ icon, temp, city, country, lat, log, humidity,


windspeed }) => {

return (

<div>

<div className='image'>

<img src={icon} alt="image" />

</div>

<div className="temper">{temp}°C</div>

38
<div className="city">{city}</div>

<div className="country">{country}</div>

<div className="cord">

<div>

<span className='lat'>Latitude</span>

<span>{lat}</span>

</div>

<div>

<span className='log'>Longitude</span>

<span>{log}</span>

</div>

</div>

<div className="cord2">

<div>

<img src={HumidityIcon} alt="" className='humidity-icon' />

<span>{humidity}%</span>

<span>Humidity</span>

</div>

<div>

<img src={WindIcon} alt="" className='wind-icon' />

<span>{windspeed} km/h</span>

<span>Wind Speed</span>

39
</div>

</div>

</div>

export const App = () => {

let api_key = "78689eb2f5afefe5eb2b504c2f8189fa";

const [text, setText] = useState("Pudukkottai");

const [icon, setIcon] = useState(SunIcon);

const [temp, setTemp] = useState(32);

const [city, setCity] = useState("Pudukkottai");

const [country, setCountry] = useState("India");

const [lat, setLat] = useState(32);

const [log, setLog] = useState(32);

const [humidity, setHumidity] = useState(0);

const [windspeed, setWindspeed] = useState(0);

const [cityNotFound, setCityNotFound] = useState(false);

const [loading, setLoading] = useState(false);

const weatherIconMap = {

"01d" : SunIcon,

"01n" : SunIcon,

40
"02d" : CloudWeatherIcon,

"02n" : CloudWeatherIcon,

"03d" : DrizzleIcon,

"03n" : DrizzleIcon,

"04d" : DrizzleIcon,

"04n" : DrizzleIcon,

"09d" : RainIcon,

"09n" : RainIcon,

"010d" : RainIcon,

"010n" : RainIcon,

"013d" : SnowIcon,

"013n" : SnowIcon,

const search = async () => {

setLoading(true);

let url =
`https://api.openweathermap.org/data/2.5/weather?q=${text}&appid=${api_key
}&units=Metric`;

try {

let res = await fetch(url);

let data = await res.json();

if(data.cod === "404"){

41
console.log("City not found ra thambi");

setCityNotFound(true);

setLoading(false);

setLat(data.coord.lat);

setLog(data.coord.lon);

setCity(data.name);

setHumidity(data.main.humidity);

setWindspeed(data.wind.speed);

setTemp(Math.floor(data.main.temp));

setCountry(data.sys.country)

const weatherIcon = data.weather[0].icon;

setIcon(weatherIconMap[weatherIcon] || SunIcon);

setCityNotFound(false);

} catch (error) {

console.error("An error Occured : ", error.message);

} finally {

setLoading(false);

const searchHandler = (e) => {

setText(e.target.value);

42
}

const onKeyHandler = (e) => {

if (e.key === "Enter") {

search();

useEffect(function () {

search();

},[]);

return (

<div className='main'>

<div className='container'>

<div className='search'>

<input type="text" placeholder='Search' onChange={searchHandler}


value={text} onKeyDown={onKeyHandler} />

<img src={SearchIcon} alt="" className='img-search' onClick={() =>


search()} />

</div>

{cityNotFound && <div className='citynot'>City Not Found</div>}

{!loading && !cityNotFound && <WeatherDetails icon={icon} temp={temp}


city={city} country={country} lat={lat} log={log} humidity={humidity}
windspeed={windspeed} />}

{loading && <p className='loading'>Loading....</p>}

43
{/* <p className='designed'>Designed by <span>KATHIRESAN</span></p>
*/}

</div>

</div>

3)main.jsx

import React from 'react'

import ReactDOM from 'react-dom/client'

import { App } from './App.jsx'

ReactDOM.createRoot(document.getElementById('root')).render(

<React.StrictMode>

<App />

</React.StrictMode>,

4)index.html

<!doctype html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<link rel="icon" type="image" href="./src/assets/weather-app.png" />

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

44
<title>Web Application</title>

</head>

<body>

<div id="root"></div>

<script type="module" src="/src/main.jsx"></script>

</body>

</html>

5)package.json

"name": "mk-weather-app",

"private": true,

"version": "0.0.0",

"type": "module",

"scripts": {

"dev": "vite",

"build": "vite build",

"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",

"preview": "vite preview"

},

"dependencies": {

"react": "^18.2.0",

"react-dom": "^18.2.0"

45
},

"devDependencies": {

"@types/react": "^18.2.56",

"@types/react-dom": "^18.2.19",

"@vitejs/plugin-react": "^4.2.1",

"eslint": "^8.56.0",

"eslint-plugin-react": "^7.33.2",

"eslint-plugin-react-hooks": "^4.6.0",

"eslint-plugin-react-refresh": "^0.4.5",

"vite": "^5.1.4"

46
APPENDIX

SCREENSHOTS

OUTPUT:

Default Home page

47
Search City

City Not Found

48
REFERENCE

API’s:

1.Open Weather Map API:Provides Current Weather Conditions,Forecast and


historical data.

2.Weather API:Offers Current Weather Conditions and Forecast.

3.Dark Sky API:Provides hyperlocal weather forecast and current weather


condition.

ONLINE RESOURCES:

1.National weather service (NWS):Provides current Weather Conditions and


Forecast and alerts.

2.world meterological organizations (WMO): Provides current Weather


Conditions and Forecast and alerts for location world wide.

3.Weather Underground: Provides current Weather Conditions and Forecast and


world wide.

RESEARCH PAPERS:

1.”A survey of weather forecasting technique” by s.s Iyengar et al.(2019) -


Covers various weather forecasting technique.

2.”Deep learning for weather forecasting” by j.liu et al.(2020) -Covers the


application of deep learning technique for weather forecasting.

49
CONCLUSION

The Current Weather Checking API is a robust and reliable solution for
developers seeking to integrate accurate and real-time weather data into their
applications. By providing instant access to current weather conditions, forecasts,
and weather alerts, this API enables developers to build innovative and user-
centric applications that cater to various industries, including weather forecasting,
travel, tourism, smart home automation, and more. The API's ability to deliver
precise and up-to-date weather information empowers developers to enhance user
experiences, improve decision-making, and drive business growth. Furthermore,
the Current Weather Checking API's scalability, flexibility, and ease of integration
make it an ideal choice for developers seeking to create cutting-edge applications
that meet the evolving needs of their users.

50

You might also like