From bf22fd6c8514a0ca56a0eeb4042e9fc56c9c1b46 Mon Sep 17 00:00:00 2001 From: Vinzenz Schroeter Date: Mon, 29 Apr 2024 13:27:35 +0200 Subject: [PATCH] useMutation for map chooser --- tank-frontend/src/MapChooser.tsx | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/tank-frontend/src/MapChooser.tsx b/tank-frontend/src/MapChooser.tsx index 9564dfa..00923e2 100644 --- a/tank-frontend/src/MapChooser.tsx +++ b/tank-frontend/src/MapChooser.tsx @@ -1,7 +1,7 @@ import {ChangeEvent} from 'react'; import {makeApiUrl} from './serverCalls'; import './MapChooser.css'; -import {useQuery} from '@tanstack/react-query'; +import {useMutation, useQuery} from '@tanstack/react-query'; export default function MapChooser() { const query = useQuery({ @@ -15,20 +15,31 @@ export default function MapChooser() { } }); + const postMap = useMutation({ + retry: false, + mutationFn: async (map: string) => { + const url = makeApiUrl('/map'); + url.searchParams.set('name', map); + + const response = await fetch(url, {method: 'POST'}); + if (!response.ok) + throw new Error(`${response.status} (${response.statusText}): ${await response.text()}`); + } + }); + const onChange = (event: ChangeEvent) => { if (event.target.selectedIndex < 1) return; event.preventDefault(); - const url = makeApiUrl('/map'); - url.searchParams.set('name', event.target.options[event.target.selectedIndex].value); - - fetch(url, {method: 'POST'}); + const chosenMap = event.target.options[event.target.selectedIndex].value; + postMap.mutate(chosenMap); }; - return - {query.isSuccess && query.data.map(m => - )} + {query.isSuccess && query.data.map(m => )} ; }