Files
CityExplorer/locationStore.js
2025-05-15 00:06:38 +02:00

75 lines
1.7 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);
set((state) => ({
locations: [...state.locations, newLoc],
loading: false,
}));
return newLoc;
} 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,
}));
if(deleted) {
return true;
}
} catch (error) {
set({ error, loading: false });
return false;
}
},
getLocation: (id) => {
return get().locations.find((loc) => String(loc.id) === String(id));
},
}));
export default useLocationStore;