Skip to content

Commit

Permalink
use react forms
Browse files Browse the repository at this point in the history
  • Loading branch information
minhd-vu committed Feb 26, 2024
1 parent 372c3cd commit e60b309
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 17 deletions.
32 changes: 15 additions & 17 deletions components/JoinParty.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
"use client";

import { FormEvent } from "react";
import { useContext } from "react";
import { SubmitHandler, useForm } from "react-hook-form";
import { useSWRConfig } from "swr";
import { ErrorContext } from "./App";

type Inputs = {
code: string;
};

export default function JoinParty() {
const { mutate } = useSWRConfig();
const { register, handleSubmit } = useForm<Inputs>();
const { setError } = useContext(ErrorContext);

async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();

const data = new FormData(event.currentTarget);
const value = data.get("code");
if (!value) {
throw new Error();
}

const code = value.toString().toLowerCase();
const onSubmit: SubmitHandler<Inputs> = async ({ code }) => {
const res = await fetch("/api/party/join", {
method: "POST",
headers: {
Expand All @@ -25,18 +24,17 @@ export default function JoinParty() {
});

if (!res.ok) {
throw new Error(await res.json());
setError(await res.json());
return;
}

mutate("/api/user");
}
};

return (
<form onSubmit={onSubmit}>
<form onSubmit={handleSubmit(onSubmit)}>
<input
type="text"
id="code"
name="code"
{...register("code")}
className="input input-bordered"
placeholder="Party Code"
required
Expand Down
16 changes: 16 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"next-themes": "^0.2.1",
"react": "^18",
"react-dom": "^18",
"react-hook-form": "^7.50.1",
"swr": "^2.2.5"
},
"devDependencies": {
Expand Down

0 comments on commit e60b309

Please sign in to comment.