add Zustand and del unnecessary files
This commit is contained in:
75
locationStore.js
Normal file
75
locationStore.js
Normal file
@@ -0,0 +1,75 @@
|
||||
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;
|
||||
Reference in New Issue
Block a user