Files
CityExplorer/locationStore.js
2025-05-24 09:00:48 +02:00

84 lines
2.3 KiB
JavaScript

import {create} from "zustand";
import * as api from "@/api/locations";
const useLocationStore = create((set, get) => ({
locations: [],
loading: false,
error: null,
fetchLocations: async () => {
set({loading: true, error: null});
try {
const data = await api.listLocations();
set({locations: data, loading: false});
} catch (error) {
set({error, loading: false});
}
},
addLocation: async (location) => {
set({loading: true, error: null});
try {
const newLoc = await api.addLocation(location);
const normalizedLoc = {
...newLoc,
imageSource: api.normalizeImageSource(newLoc.image)
};
set((state) => ({
locations: [...state.locations, normalizedLoc],
loading: false,
}));
return normalizedLoc;
} catch (error) {
set({error, loading: false});
return null;
}
},
updateLocation: async (id, location) => {
set({loading: true, error: null});
try {
const updated = await api.updateLocation(id, location);
set((state) => ({
locations: state.locations.map((loc) =>
loc.id === id ? updated : loc
),
loading: false,
}));
return updated;
} catch (error) {
set({error, loading: false});
return null;
}
},
deleteLocation: async (id) => {
set({loading: true, error: null});
try {
const deleted = await api.deleteLocation(id);
set((state) => ({
locations: state.locations.filter((loc) => loc.id !== id),
loading: false,
}));
return deleted;
} catch (error) {
set({error, loading: false});
return false;
}
},
getLocation: (id) => {
const location = get().locations.find((loc) => String(loc.id) === String(id));
if (location && !location.imageSource) {
return {
...location,
imageSource: api.normalizeImageSource(location.image)
};
}
return location;
},
}));
export default useLocationStore;