Created
February 23, 2021 05:38
-
-
Save carlrip/c048b9cad627fde1836a55ac24a31474 to your computer and use it in GitHub Desktop.
Update Requests with React Query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { useQuery, useMutation } from "react-query"; | |
type Person = { | |
id: number; | |
firstName: string; | |
lastName: string; | |
}; | |
async function getPerson({ queryKey }: { queryKey: [string, { id: number }] }) { | |
const [, { id }] = queryKey; | |
const response = await fetch(`http://localhost:3004/people/${id}`); | |
if (!response.ok) { | |
throw Error("Problem fetching person"); | |
} | |
const data = await response.json(); | |
assertIsPerson(data); | |
return data; | |
} | |
function assertIsPerson(data: any): asserts data is Person { | |
if (!("id" in data && "firstName" in data && "lastName" in data)) { | |
throw new Error("Not a person"); | |
} | |
} | |
export function App() { | |
const { status: queryStatus, error: queryError, data } = useQuery< | |
Person, | |
Error | |
>(["person", { id: 1 }], getPerson); | |
const { mutate, status: mutateStatus, error: mutateError } = useMutation< | |
Person, // return type | |
Error, | |
Person // params type | |
>(updatePerson); | |
if (queryStatus === "loading") { | |
return <div>...</div>; | |
} | |
if (queryStatus === "error") { | |
return <div>{queryError!.message}</div>; | |
} | |
function handleSubmit(e: React.FormEvent<HTMLFormElement>) { | |
e.preventDefault(); | |
const formData = new FormData(e.target as HTMLFormElement); | |
const firstName = formData.get("firstName") as string; | |
const lastName = formData.get("lastName") as string; | |
mutate({ id: data!.id, firstName, lastName }); | |
} | |
return ( | |
<div> | |
{data && ( | |
<form onSubmit={handleSubmit}> | |
<p>ID: {data.id}</p> | |
<fieldset disabled={mutateStatus === "loading"}> | |
<div> | |
<label htmlFor="firstName">First name</label> | |
<input | |
type="text" | |
id="firstName" | |
name="firstName" | |
defaultValue={data.firstName} | |
/> | |
</div> | |
<div> | |
<label htmlFor="lastName">Last name</label> | |
<input | |
type="text" | |
id="lastName" | |
name="lastName" | |
defaultValue={data.lastName} | |
/> | |
</div> | |
</fieldset> | |
<button type="submit">Save</button> | |
</form> | |
)} | |
{mutateStatus === "success" && <p>Change successfully saved</p>} | |
{mutateStatus === "error" && <p>{mutateError!.message}</p>} | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment