Experiment 8
Create a service in react that fetches the weather information from open weathermap.org and the
display the current and historical weather information using graphical representation using chart.js
Aim:
To create a React service that fetches weather information from openweathermap.org and displays
current and historical weather data using Chart.js.
Objective:
1. To call APIs into a React application.
2. To display weather data graphically using Chart.js.
Procedure:
Step 1:
Install Node.js from https://nodejs.org/en.
Step 2:
Create a new folder and open that folder in VS code.
Step 3:
Open the terminal in VS Code and install react by typing “npx create-react-app weather-info”.
Step 4:
Install chart.js by typing “npm install react-chartjs-2 chart.js”.
Step 5:
Remove the code in App.js and write the corresponding code and create separate components.
Step 6:
Register all the required components (like scales, elements, plugins) by typing
“Chart.register(...registerables)” in the functional component.
Step 6:
Open the terminal and run the program by typing “npm start”.
Code Snippet:
App.js:
import logo from './logo.svg';
import './App.css';
import WeatherInfo from './WeatherInfo';
function App() {
return (
<div className="App">
<WeatherInfo/>
</div>
);
export default App;
WeatherInfo.js :
import React, { useState } from 'react'
import { Chart, registerables } from 'chart.js'
const WeatherInfo = () => {
let [city,setCity]=useState('')
Chart.register(...registerables);
async function weatherInfo (event) {
event.preventDefault()
console.log("hi")
let data = await weatherData(city)
if(data!== null) {
let [time,temp]=weatherParameters(data)
displayData(time,temp)
}
}
function displayData(time,temp) {
const ctx = document.getElementById('myChart');
new Chart(ctx, {
type: 'line',
data: {
labels: time,
datasets: [{
label: 'temperature',
data: temp,
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: false
});
function weatherParameters (data) {
let time = data.list.map((item)=> new Date(item.dt_txt).toLocaleTimeString())
let temp = data.list.map((item)=>item.main.temp)
console.log(time)
console.log(temp)
return [time,temp]
async function weatherData (city) {
console.log(city)
let url = `http://api.openweathermap.org/data/2.5/forecast?q=$
{city}&appid=5b94931e44a65712481859273e13a972&units=metric`;
try {
let response = await fetch(url)
let data = await response.json()
if (data.cod == '200') {
return data
else {
alert("city not found")
return null
} catch (error) {
console.error("error",error)
return null
function updateCity (e) {
setCity(e.target.value)
return (
<div>
<h1>Weather Report</h1>
<form>
<input type='text' onChange={updateCity}/>
<button onClick={weatherInfo}>Get Weather Report</button>
</form>
<canvas id='myChart'></canvas>
</div>
export default WeatherInfo
Conclusion:
Successfully implemented a React service to fetch weather data and displayed using Chart.js.