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, radarLatestURL: null, radarLoopURL: null, } } export const useWeatherStore = defineStore('weather', { state: () => { return getDefaults() }, actions: { clearWeather() { this.setCoordinates(null) this.setCityState(null) this.setWeather(null) this.setForecast(null) this.radarLatestURL = null this.radarLoopURL = 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) } const station = weather.properties.radarStation this.radarLatestURL = `https://radar.weather.gov/ridge/standard/${station}_0.gif` this.radarLoopURL = `https://radar.weather.gov/ridge/standard/${station}_loop.gif` 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 }, }, })