From 581fd5dd7bae58b2e792aae05ffaaa4686b2715a Mon Sep 17 00:00:00 2001 From: Drew Rautenberg Date: Mon, 20 Jan 2025 21:13:17 -0600 Subject: [PATCH] form stuff pt2 --- barkmanui/src/features/inventory/EditItem.tsx | 60 +++++++++++++++---- 1 file changed, 49 insertions(+), 11 deletions(-) diff --git a/barkmanui/src/features/inventory/EditItem.tsx b/barkmanui/src/features/inventory/EditItem.tsx index 3859a82..f54dbb6 100644 --- a/barkmanui/src/features/inventory/EditItem.tsx +++ b/barkmanui/src/features/inventory/EditItem.tsx @@ -1,14 +1,17 @@ import {Button, Group, TextInput, Text, Textarea, NumberInput} from '@mantine/core'; import { useForm } from '@mantine/form'; import {useParams} from "react-router"; -import {useQuery} from "@tanstack/react-query"; +import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query"; import {InventoryItem} from "./types.ts"; import {useEffect} from "react"; +import {put} from "axios"; + +type EditableInventoryItem = Omit; function EditItem() { const params = useParams(); - const form = useForm({ + const form = useForm({ mode: 'uncontrolled', initialValues: { name: "", @@ -25,6 +28,8 @@ function EditItem() { }); + + const { isPending, error, data, isFetching } = useQuery({ queryKey: ['inventory', params.itemId], queryFn: async (): Promise => { @@ -38,28 +43,61 @@ function EditItem() { }, }); + const queryClient = useQueryClient(); + + const updateItem = useMutation({ + mutationFn: async (values: EditableInventoryItem) => { + + // await + const result = await fetch(import.meta.env.VITE_API_URL + '/inventory/' + params.itemId, { + method: 'PUT', + body: JSON.stringify(values), + headers: { + 'Content-Type': 'application/json' + } + }); + + if (!result.ok) { + throw new Error('Failed to update inventory item'); + } + + // invalidate the queries so they pull updated information + // this is a prefix, so it covers both the query that pulls a list, and also `['inventory', itemId]` in this file + await queryClient.invalidateQueries({ + queryKey: ['inventory'] + }); + } + }) + useEffect(() => { if (data) { // Even if query.data changes, form will be initialized only once form.initialize(data); } - }, [data, form]); + }, [data]); if (isPending) return 'Loading...' if (error) return 'An error has occurred: ' + error.message return ( -
console.log(values))}> + await + updateItem.mutateAsync(values))}>
{isFetching ? 'Updating...' : ''}
ID: {data.id} - - - - - - -