Skip to content

Instantly share code, notes, and snippets.

@jinwook-k
Last active September 23, 2020 16:28
Show Gist options
  • Save jinwook-k/6355cdf4937d806e68bd628f847f410d to your computer and use it in GitHub Desktop.
Save jinwook-k/6355cdf4937d806e68bd628f847f410d to your computer and use it in GitHub Desktop.
client/src/Components/WeatherForm.jsx
// other imports
import axios from 'axios';
class WeatherForm extends Component {
// default state values
componentDidMount() {
this.refreshSavedWeather();
}
// Refreshes the current weather data for the most recent zip code, if it exists
refreshSavedWeather = () => {
if (localStorage.getItem("zipCode")) {
axios.post("/api/weather", {
zipCode: localStorage.getItem("zipCode"),
tempMetric: localStorage.getItem("tempMetric")
}).then(d => {
localStorage.setItem("CurrentWeatherData", JSON.stringify(d.data));
});
}
}
// onChange()
saveFormData = (event) => {
event.preventDefault();
// Gets the weather data from the weather api and returns it to save into local storage and redux store.
axios.post("/api/weather", {
zipCode: this.state.zipCodeInput,
tempMetric: this.state.tempMetric
}).then(response => {
let weatherData = response.data;
this.saveToLocalStorage(weatherData);
});
}
// Save data from form to local storage
saveToLocalStorage = (weatherData) => {
localStorage.setItem("zipCode", this.state.zipCodeInput);
localStorage.setItem("tempMetric", this.state.tempMetric);
localStorage.setItem("CurrentWeatherData", JSON.stringify(weatherData));
}
render() {
return (
<Form className="weather-form" onSubmit={this.saveFormData}>
...
</Form>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment