Skip to content

Commit

Permalink
refactor: continue replacing current localStorage usage with new store (
Browse files Browse the repository at this point in the history
#71)

* Move last_currency_used to store

* Move recent_locations to store
  • Loading branch information
raphodn authored Dec 26, 2023
1 parent 9b44534 commit 2bbdd3c
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 83 deletions.
19 changes: 10 additions & 9 deletions src/components/LocationSelector.vue
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,10 @@
</template>

<script>
import "leaflet/dist/leaflet.css"
import { LMap, LTileLayer, LMarker, LPopup } from "@vue-leaflet/vue-leaflet"
import 'leaflet/dist/leaflet.css'
import { LMap, LTileLayer, LMarker, LPopup } from '@vue-leaflet/vue-leaflet'
import { mapStores } from 'pinia'
import { useAppStore } from '../store'
import api from '../services/api'
export default {
Expand All @@ -104,7 +106,6 @@ export default {
},
loading: false,
results: null,
recentLocations: api.getRecentLocations(),
// map
map: null,
mapZoom: 5,
Expand All @@ -113,12 +114,13 @@ export default {
}
},
computed: {
...mapStores(useAppStore),
formFilled() {
return Object.values(this.locationSearchForm).every(x => !!x)
},
// recentLocations() { // TODO: make reactive
// return api.getRecentLocations()
// },
recentLocations() {
return this.appStore.getRecentLocations()
},
},
methods: {
fieldRequired(v) {
Expand Down Expand Up @@ -166,11 +168,10 @@ export default {
return locationTitle
},
clearRecentLocations() {
api.clearRecentLocations()
this.recentLocations = []
this.appStore.clearRecentLocations()
},
selectLocation(location) {
api.addRecentLocation(location)
this.appStore.addRecentLocation(location)
this.$emit('location', location)
this.close()
},
Expand Down
65 changes: 1 addition & 64 deletions src/services/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,6 @@ import { useAppStore } from '../store'

const NOMINATIM_SEARCH_URL = 'https://nominatim.openstreetmap.org/search'
const NOMINATIM_RESULT_TYPE_EXCLUDE_LIST = ['fuel', 'gas', 'casino']
const RECENT_LOCATIONS_LOCAL_STORAGE_KEY = 'recent_locations'
const LAST_CURRENCY_USED_LOCAL_STORAGE_KEY = 'last_currency_used'


function getOrCreateLocalStorageItem(itemKey, defaultValue='') {
if (!localStorage.getItem(itemKey)) {
localStorage.setItem(itemKey, JSON.stringify(defaultValue))
}
return localStorage.getItem(itemKey)
}

function clearLocalStorageItem(itemKey, defaultValue='') {
return localStorage.setItem(itemKey, JSON.stringify(defaultValue))
}

function getParsedLocalStorageItem(itemKey, defaultValue='') {
let item = getOrCreateLocalStorageItem(itemKey, defaultValue)
return JSON.parse(item)
}

function setValueToLocalStorageItem(itemKey, value) {
return localStorage.setItem(itemKey, JSON.stringify(value))
}

function addObjectToLocalStorageItemArray(itemKey, obj, unshift=false, avoidDuplicates=true) {
let itemJSON = getParsedLocalStorageItem(itemKey, [])
// look for duplicate
var duplicateItem = itemJSON.findIndex(item => JSON.stringify(item) === JSON.stringify(obj))
if (avoidDuplicates && duplicateItem >= 0) {
itemJSON.splice(duplicateItem, 1)
}
// add obj to array
if (unshift) {
itemJSON.unshift(obj)
} else {
itemJSON.push(obj)
}
return localStorage.setItem(itemKey, JSON.stringify(itemJSON))
}


export default {
signIn(username, password) {
Expand Down Expand Up @@ -72,6 +32,7 @@ export default {

createPrice(priceData) {
const store = useAppStore()
store.user.last_currency_used = priceData.currency
return fetch(`${import.meta.env.VITE_OPEN_PRICES_API_URL}/prices`, {
method: 'POST',
headers: {
Expand Down Expand Up @@ -123,28 +84,4 @@ export default {
.then((response) => response.json())
.then((data) => data.filter(l => !NOMINATIM_RESULT_TYPE_EXCLUDE_LIST.includes(l.type)))
},

getRecentLocations(limit=null) {
let recentLocations = getParsedLocalStorageItem(RECENT_LOCATIONS_LOCAL_STORAGE_KEY, [])
if (limit && recentLocations.length && recentLocations.length > limit) {
return recentLocations.slice(0, limit)
}
return recentLocations
},

addRecentLocation(location) {
return addObjectToLocalStorageItemArray(RECENT_LOCATIONS_LOCAL_STORAGE_KEY, location, true)
},

clearRecentLocations() {
clearLocalStorageItem(RECENT_LOCATIONS_LOCAL_STORAGE_KEY, [])
},

getLastCurrencyUsed() {
return getParsedLocalStorageItem(LAST_CURRENCY_USED_LOCAL_STORAGE_KEY, 'EUR') // TODO: init with user locale?
},

setLastCurrencyUsed(currency) {
return setValueToLocalStorageItem(LAST_CURRENCY_USED_LOCAL_STORAGE_KEY, currency)
},
}
22 changes: 20 additions & 2 deletions src/store.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
import { defineStore } from 'pinia'
import utils from './utils.js'

export const useAppStore = defineStore('app', {
state: () => ({
user: {
username: null,
token: null,
last_currency_used: 'EUR', // TODO: init with user locale ?
recent_locations: [],
},
}),
getters: {},
getters: {
getRecentLocations: (state) => {
return (limit=null) => {
if (limit && state.user.recent_locations.length && state.user.recent_locations.length > limit) {
return state.user.recent_locations.slice(0, limit)
}
return state.user.recent_locations
}
}
},
actions: {
signIn(username, token) {
this.user.username = username
Expand All @@ -16,7 +28,13 @@ export const useAppStore = defineStore('app', {
signOut() {
this.user.username = null
this.user.token = null
}
},
addRecentLocation(location) {
this.user.recent_locations = utils.addObjectToArray(this.user.recent_locations, location, true)
},
clearRecentLocations() {
this.user.recent_locations = []
},
},
// pinia-plugin-persistedstate
persist: {
Expand Down
18 changes: 18 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
function addObjectToArray(arr, obj, unshift = false, avoidDuplicates = true) {
// look for duplicate
var duplicateItem = arr.findIndex(item => JSON.stringify(item) === JSON.stringify(obj))
if (avoidDuplicates && duplicateItem >= 0) {
arr.splice(duplicateItem, 1)
}
// add obj to array
if (unshift) {
arr.unshift(obj)
} else {
arr.push(obj)
}
return arr
}

export default {
addObjectToArray,
}
23 changes: 15 additions & 8 deletions src/views/AddPriceSingle.vue
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@

<script>
import Compressor from 'compressorjs'
import { mapStores } from 'pinia'
import { useAppStore } from '../store'
import constants from '../constants'
import api from '../services/api'
import BarcodeScanner from '../components/BarcodeScanner.vue'
Expand All @@ -179,7 +181,7 @@ export default {
proof_id: null,
product_code: '',
price: null,
currency: api.getLastCurrencyUsed(),
currency: null, // see initPriceSingleForm
location_osm_id: null,
location_osm_type: '',
date: new Date().toISOString().substr(0, 10)
Expand All @@ -195,12 +197,12 @@ export default {
// price data
currencyList: constants.CURRENCY_LIST,
// location data
recentLocations: api.getRecentLocations(3),
locationSelector: false,
locationSelectedDisplayName: ''
};
},
computed: {
...mapStores(useAppStore),
proofFormFilled() {
let keys = ['proof_id']
return Object.keys(this.addPriceSingleForm).filter(k => keys.includes(k)).every(k => !!this.addPriceSingleForm[k])
Expand All @@ -209,6 +211,9 @@ export default {
let keys = ['product_code', 'price', 'currency']
return Object.keys(this.addPriceSingleForm).filter(k => keys.includes(k)).every(k => !!this.addPriceSingleForm[k])
},
recentLocations() {
return this.appStore.getRecentLocations(3)
},
locationFormFilled() {
let keys = ['location_osm_id', 'location_osm_type']
return Object.keys(this.addPriceSingleForm).filter(k => keys.includes(k)).every(k => !!this.addPriceSingleForm[k])
Expand All @@ -219,12 +224,18 @@ export default {
},
formFilled() {
return Object.values(this.addPriceSingleForm).every(x => !!x)
}
},
},
mounted() {
this.initPriceSingleForm()
},
methods: {
fieldRequired(v) {
return !!v
},
initPriceSingleForm() {
this.addPriceSingleForm.currency = this.appStore.user.last_currency_used
},
clearProof() {
this.proofImage = null
this.proofImagePreview = null
Expand Down Expand Up @@ -275,7 +286,6 @@ export default {
if (data['detail']) {
alert(`Error: with input ${data['detail'][0]['input']}`)
} else {
api.setLastCurrencyUsed(this.addPriceSingleForm.currency)
this.$router.push({ path: '/add', query: { singleSuccess: 'true' } })
}
this.createPriceLoading = false
Expand All @@ -297,12 +307,9 @@ export default {
},
closeLocationSelector(event) {
this.locationSelector = false
setTimeout(() => { // TODO: replace with store (make recentLocations reactive)
this.recentLocations = api.getRecentLocations(3)
}, 50)
},
setLocationData(event) {
api.addRecentLocation(event)
this.appStore.addRecentLocation(event)
this.locationSelectedDisplayName = event.display_name
this.addPriceSingleForm.location_osm_id = event.osm_id
this.addPriceSingleForm.location_osm_type = event.osm_type.toUpperCase()
Expand Down

0 comments on commit 2bbdd3c

Please sign in to comment.