Skip to content

Commit

Permalink
Merge branch 'kiran-sessions' of https://github.com/Panda-Whale-Enter…
Browse files Browse the repository at this point in the history
…prises/weather-app into kiran-sessions
  • Loading branch information
kiranbanger committed Aug 18, 2022
2 parents 8e8e636 + 8f7b3fb commit eae1b68
Show file tree
Hide file tree
Showing 10 changed files with 151 additions and 115 deletions.
6 changes: 3 additions & 3 deletions .env
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MONGOUSER=user
MONGOPASSWORD=1234

SALTROUNDS=10

SECRET=secretkey
SECRET=secretkey
GOOGLEAPIKEY=AIzaSyBayyrcjqLP9vwFjtnMAl7Kylud3Y1HufM
METEOSTATKEY=d347064809msh514a2d058576195p1817f9jsnd9e6df5ef747
53 changes: 51 additions & 2 deletions client/components/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,62 @@ import { Routes, Route } from "react-router-dom";
const App = props => {

const [user, setUser] = useState(null);
const [localInfo, setLocalInfo] = useState({});
const [currInfoLoading, setCurrInfoLoading] = useState(true);
const [locationToLoad, setLocationToLoad] = useState(false);


useEffect(()=>{
const currentLocationInfo = (() => {
let api = "https://api.openweathermap.org/data/2.5/weather";
let apiKey = "3865d44fbc4bfd45572787afb8fa06b2";

navigator.geolocation.getCurrentPosition(success, error);

function success(position){
setLocationToLoad(true);
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
let url = `${api}?lat=${latitude}&lon=${longitude}&appid=${apiKey}&units=imperial`;

let localInfo = {}

fetch(url)
.then(res => res.json())
.then(data => {
localInfo.temp = data.main.temp;
localInfo.currentLocation = data.name
localInfo.weatherDescription = data.weather[0].main;
localInfo.latitude = latitude
localInfo.longitude = longitude

setLocalInfo(localInfo)
setCurrInfoLoading(false);
})
};

function error() {
console.log('error finding location');
setCurrInfoLoading(false);
}
})();
}, [])

return (
<Routes>
<Route path="/" element={
<main>
<Navbar user={user} setUser={setUser} />
<LocalWeather />
<Searchbar user={user} setUser={setUser} />
<LocalWeather localInfo = {localInfo}/>
{!currInfoLoading ?
<Searchbar
localInfo={localInfo}
locationToLoad={locationToLoad}
setLocationToLoad={setLocationToLoad}
user={user}
setUser={setUser} /> :
<div className="searchbar"><h3>Loading Location Info</h3></div>
}
</main>
} />
<Route path="/signup" element={<Signup user={user} setUser={setUser} />} />
Expand All @@ -32,3 +80,4 @@ const App = props => {

export default App;


6 changes: 3 additions & 3 deletions client/components/Card.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,14 @@ const Card = (props) => {
}, []);

useEffect(() => {
console.log("Card.jsx useEffect cityData: ", cityData);
console.log("Card.jsx useEffect cityName: ", cityName);
// console.log("Card.jsx useEffect cityData: ", cityData);
// console.log("Card.jsx useEffect cityName: ", cityName);
}, [cityData, cityName]);

return (
<div className="card">
<div className="card-header">
<h3>City Name: {cityName.toUpperCase()}</h3>
<h3>Location Name: {cityName.toUpperCase()}</h3>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
Expand Down
2 changes: 0 additions & 2 deletions client/components/CardContainer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@ import Card from './Card.jsx';


const CardContainer = (props) => {

return (
<div className='cardContainer-div'>
<h2>Average Temperature</h2>
<div className='cardContainer'>
<Card city={props.city} data={props.data}/>
</div>

</div>
)
}
Expand Down
58 changes: 12 additions & 46 deletions client/components/LocalWeather.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import axios from "axios";

import React from "react";
import { FunnelChart } from "recharts";

Expand All @@ -7,53 +7,19 @@ import { FunnelChart } from "recharts";

const LocalWeather = props => {



const getWeather = () => {

let api = "https://api.openweathermap.org/data/2.5/weather";
let apiKey = "3865d44fbc4bfd45572787afb8fa06b2";


navigator.geolocation.getCurrentPosition(success, error);

function success(position){
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
let url = `${api}?lat=${latitude}&lon=${longitude}&appid=${apiKey}&units=imperial`;

fetch(url)
.then(res => res.json())
.then(data => {

let location = document.getElementById("location")
let temperature = document.querySelector('#temperature');
let description = document.querySelector('#description')

let temp = data.main.temp;
temperature.innerHTML = temp + "° F";
location.innerHTML = data.name;
description.innerHTML = data.weather[0].main;
})
// console.log('position ', position);
// console.log('latitude: ', latitude);
// console.log('longitude: ', longitude);
// console.log('url: ', url)
};

function error(){console.log('error finding location')}



}

getWeather()

return(
<div className="localWeather">
<h3 id="location">Location</h3>
<h4 id='temperature'>Temp</h4>
<h4 id='description'>Description</h4>
<h3 id="location">{
props.localInfo.currentLocation ?
props.localInfo.currentLocation :
'No Local Data Available'
}</h3>
<h4 id='temperature'>{
props.localInfo.temp ?
props.localInfo.temp + ' °F' :
'Current Temperature Unavailable'
}</h4>
<h4 id='description'>{props.localInfo.weatherDescription}</h4>

</div>
)
Expand Down
103 changes: 59 additions & 44 deletions client/components/Searchbar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,67 +5,82 @@ import CardContainer from './CardContainer.jsx';
import { LineChart } from 'recharts';

const Searchbar = props => {

//[current, updateMethod] = usesState('default')

const [cityData, setCityData] = useState([]) // cityData = []
const [isClicked, setIsClicked] = useState(false) // isClicked = true/false
const [cityName, setCityName] = useState('') // cityName = 'Portland'

//like componentDidMount triggers on change
useEffect(() => {
//console.log('cityData in useEffect: ', cityData)
//console.log('cityName in useEffect: ', cityName)
}, [cityData, cityName])


const handleClicked = () => {
// isClicked = false
// reset isclicked to false
// console.log('isclicked is: ', isClicked);
isClicked ? setIsClicked(false) : setIsClicked(true)
// console.log('handleClicked after: ', isClicked)
}


const handleSubmit = (e) => {
//prevents the page from refreshing on submit
e.preventDefault();
const [cityData, setCityData] = useState([]);
const [cityName, setCityName] = useState('');
const [locationIsLoading, setLocationIsLoading] = useState(true);
const [error, setError] = useState('');

//console.log('handleSubmit e.target.firstChild.value: ', e.target.firstChild.value)

//first determine is the input is a single city (string) or multiple citys (array of strings)
//if e.target.firstChild.value is an array....do something
//else if its just a single string, assign it to a const
const inputCity = e.target.firstChild.value;
//store the input value in a const
//setInputCity(e.target.firstChild.value)
//console.log('handleSubmit inputCity: ', inputCity)

//write HTTP request and save location data in our database
// function to handle async GET requests to DB
const useAsyncData = (city) => {
axios({
method: 'POST',
url: 'http://localhost:3000/search',
data: { city: inputCity }
data: { city }
})
.then(data => {
console.log('front end!!', data);
if (data.data.cityData.length === 0) {
setError(`Weather data not found for ${data.data.cityName}, please enter a different location.`);
setLocationIsLoading(false);
props.setLocationToLoad(false);
return;
}
setCityData(data.data.cityData);
setCityName(data.data.cityName);
handleClicked();
setLocationIsLoading(false);
})
.catch(err => {
console.log('Error in post request for location data:', err);
setError('City not found, please enter a different location.');
setLocationIsLoading(false);
props.setLocationToLoad(false);
})
}


//like componentDidMount triggers on change
useEffect(() => {
if (props.locationToLoad) {
const loadData = async () => {
await useAsyncData(props.localInfo.currentLocation);
}
loadData();
} else {
setLocationIsLoading(false);
}
}, []);

const handleSubmit = (e) => {
//prevents the page from refreshing on submit
e.preventDefault();
if (!locationIsLoading) {
setError('');
setLocationIsLoading(true);
props.setLocationToLoad(true);
const inputCity = e.target.firstChild.value;
const loadData = async () => {
await useAsyncData(inputCity);
}
loadData();
}
}

return (
<div className="searchbar-div">



<form className="searchbar" onSubmit={handleSubmit}>
<input className="search-input" name="search-input" id="search-input" type="text" placeholder="London" required></input>
<input className="search-input" name="search-input" id="search-input" type="text" placeholder="Paris, France" required></input>
<input className="search-btn" type="submit" value="Search"></input>
</form>
{isClicked ? <CardContainer city={cityName} data={cityData} /> : <div><h3>Enter city name above...</h3></div>}
{
!locationIsLoading && props.locationToLoad ?
<CardContainer city={cityName} data={cityData} /> :
<div><h3>Enter a location above...</h3></div>
}
{
error ?
<div><h3>{error}</h3></div> :
null
}
</div>
)
}
Expand Down
18 changes: 12 additions & 6 deletions server/controllers/controller.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const axios = require('axios');
const { Location } = require('../model.js')
require('dotenv').config();

const controller = {};

Expand Down Expand Up @@ -28,13 +29,18 @@ controller.getData = (req, res, next) => {
}

controller.getCoordinates = (req, res, next) => {
const cityName = req.body.city;
res.locals.cityName = cityName;
const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${cityName}&key=AIzaSyBtfcxOznbnQFJHSdQTgsSZVRbvpOZNdKU`;
if (!res.locals.cityName) {
return next({
log: 'Error in controller.getCoordinates - no city name.',
message: 'Query for coordinates unsuccessful, check server log for details.'
});
}
const cityName = res.locals.cityName;
const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${cityName}&key=${process.env.GOOGLEAPIKEY}`;
// Get coordinates from city name
axios.get(url)
.then(response => {
const coordinates = { lat: response.data.results[0].geometry.location.lat, lon: response.data.results[0].geometry.location.lng } // returns { lat: 51.5, lon: -0.127 }
const coordinates = { lat: response.data.results[0].geometry.location.lat, lon: response.data.results[0].geometry.location.lng }
res.locals.coordinates = coordinates;
return next();
})
Expand All @@ -58,7 +64,7 @@ controller.getStations = (req, res, next) => {
url: 'https://meteostat.p.rapidapi.com/stations/nearby',
params: res.locals.coordinates,
headers: {
'X-RapidAPI-Key': 'ca2594298amsh94fb12fd4497783p1553c7jsn3ff6ba05d679',
'X-RapidAPI-Key': `${process.env.METEOSTATKEY}`,
'X-RapidAPI-Host': 'meteostat.p.rapidapi.com'
}
};
Expand Down Expand Up @@ -93,7 +99,7 @@ controller.getMonthlyData = (req, res, next) => {
units: 'imperial'
},
headers: {
'X-RapidAPI-Key': '486cee67b7msh6fe5f060a910d1ap176ef4jsncf8e8f8d110e',
'X-RapidAPI-Key': 'aae7167eabmsha14de507765a006p19b50bjsn4c06e379b10e',
'X-RapidAPI-Host': 'meteostat.p.rapidapi.com'
}
}
Expand Down
1 change: 0 additions & 1 deletion server/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ const userSchema = new Schema({
username: {type: String, required: true, unique: true},
password: {type: String, required: true},
favorites: {type: Object, required: false}

});

const User = mongoose.model('User', userSchema);
Expand Down
8 changes: 5 additions & 3 deletions server/tests/testDB.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
const mongoose = require('mongoose');
const { MongoMemoryServer } = require('mongodb-memory-server');

const mongod = async () => await MongoMemoryServer.create();
let mongod;

// Opens database for testing
const connect = async () => {

const uri = await mongod.getUri();
mongod = await MongoMemoryServer.create();

const uri = mongod.getUri();
await mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
Expand All @@ -19,7 +21,7 @@ const connect = async () => {
const closeDatabase = async () => {
await mongoose.connection.dropDatabase();
await mongoose.connection.close();
await mongod.stop();
mongod.stop();
}

const clearDatabase = async () => {
Expand Down
Loading

0 comments on commit eae1b68

Please sign in to comment.