91 lines
2.2 KiB
JavaScript
91 lines
2.2 KiB
JavaScript
![]() |
import { defineStore } from 'pinia'
|
||
|
|
||
|
|
||
|
const getDefaults = () => {
|
||
|
|
||
|
const coordinates = localStorage.getItem('weather.coordinates')
|
||
|
const cityState = localStorage.getItem('weather.cityState')
|
||
|
|
||
|
return {
|
||
|
coordinates,
|
||
|
cityState,
|
||
|
weather: null,
|
||
|
forecast: null,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
|
||
|
export const useWeatherStore = defineStore('weather', {
|
||
|
|
||
|
state: () => {
|
||
|
return getDefaults()
|
||
|
},
|
||
|
|
||
|
actions: {
|
||
|
|
||
|
clearWeather() {
|
||
|
this.setCoordinates(null)
|
||
|
this.setCityState(null)
|
||
|
this.setWeather(null)
|
||
|
this.setForecast(null)
|
||
|
},
|
||
|
|
||
|
async getWeather() {
|
||
|
|
||
|
if (!this.weather) {
|
||
|
|
||
|
const url = `https://api.weather.gov/points/${this.coordinates}`
|
||
|
const response = await fetch(url)
|
||
|
const weather = await response.json()
|
||
|
if (weather.status == 404) {
|
||
|
throw new Error(`Data not found for ${this.coordinates}`)
|
||
|
}
|
||
|
|
||
|
const city = weather.properties.relativeLocation.properties.city
|
||
|
const state = weather.properties.relativeLocation.properties.state
|
||
|
const cityState = `${city}, ${state}`
|
||
|
if (this.cityState != cityState) {
|
||
|
this.setCityState(cityState)
|
||
|
}
|
||
|
|
||
|
this.setWeather(weather)
|
||
|
}
|
||
|
|
||
|
return this.weather
|
||
|
},
|
||
|
|
||
|
async getForecast() {
|
||
|
|
||
|
if (!this.forecast) {
|
||
|
|
||
|
const weather = await this.getWeather(this.coordinates)
|
||
|
|
||
|
const url = weather.properties.forecast
|
||
|
const response = await fetch(url)
|
||
|
const forecast = await response.json()
|
||
|
this.setForecast(forecast)
|
||
|
}
|
||
|
|
||
|
return this.forecast
|
||
|
},
|
||
|
|
||
|
setCoordinates(value) {
|
||
|
this.coordinates = value
|
||
|
localStorage.setItem('weather.coordinates', value)
|
||
|
},
|
||
|
|
||
|
setCityState(value) {
|
||
|
this.cityState = value
|
||
|
localStorage.setItem('weather.cityState', value)
|
||
|
},
|
||
|
|
||
|
setWeather(value) {
|
||
|
this.weather = value
|
||
|
},
|
||
|
|
||
|
setForecast(value) {
|
||
|
this.forecast = value
|
||
|
},
|
||
|
},
|
||
|
})
|