feat: Add saveAdventure function to adventureService

The code changes include adding a new function called saveAdventure to the adventureService module. This function is responsible for sending a PUT request to the corresponding API endpoint to save an adventure. If the request is successful, the local adventure array is updated with the new data. If the request fails, an empty array is returned to allow for handling errors.
This commit is contained in:
Sean Morley
2024-05-04 15:18:20 +00:00
parent 716323657b
commit 798ce1e3e5
2 changed files with 112 additions and 30 deletions

View File

@@ -4,6 +4,8 @@
import AdventureCard from "$lib/components/AdventureCard.svelte";
import EditModal from "$lib/components/EditModal.svelte";
import MoreFieldsInput from "$lib/components/CreateNewAdventure.svelte";
import { saveAdventure } from "../../services/adventureService.js";
import SucessToast from "$lib/components/SucessToast.svelte";
export let data;
let plans: Adventure[] = [];
let isLoading = true;
@@ -16,10 +18,23 @@
let isShowingMoreFields: boolean = false;
let isShowingToast: boolean = false;
let toastAction: string = "";
let adventureToEdit: Adventure | undefined;
console.log(data);
function showToast(action: string) {
toastAction = action;
isShowingToast = true;
setTimeout(() => {
isShowingToast = false;
toastAction = "";
}, 3000);
}
function editPlan(event: { detail: number }) {
const adventure = plans.find((adventure) => adventure.id === event.detail);
if (adventure) {
@@ -32,36 +47,15 @@
isShowingMoreFields = false;
}
function savePlan(event: { detail: Adventure }) {
console.log("Event", event.detail);
let detailAdventure = event.detail;
// put request to /api/visits with id and adventure data
fetch("/api/planner", {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
detailAdventure,
}),
})
.then((response) => response.json())
.then((data) => {
console.log("Success:", data);
// update local array with new data
const index = plans.findIndex(
(adventure) => adventure.id === detailAdventure.id
);
if (index !== -1) {
plans[index] = detailAdventure;
}
adventureToEdit = undefined;
// showToast("Adventure edited successfully!");
})
.catch((error) => {
console.error("Error:", error);
});
async function savePlan(event: { detail: Adventure }) {
let newArray = await saveAdventure(event.detail, plans);
if (newArray.length > 0) {
plans = newArray;
showToast("Adventure updated successfully!");
} else {
showToast("Failed to update adventure");
}
adventureToEdit = undefined;
}
function removeAdventure(event: { detail: number }) {
@@ -124,6 +118,10 @@
};
</script>
{#if isShowingToast}
<SucessToast action={toastAction} />
{/if}
<div class="flex flex-row items-center justify-center gap-4">
<button
type="button"