0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SvelteKit初心者がForm actionsで悩んでたら、HTMLの基本を思い出した話

Last updated at Posted at 2023-03-21

TL;DR :chocolate_bar:

:warning: <form>でsubmitイベントを発火させるときは<button>にtype="submit"が指定されていることを確認しよう:exclamation:

あるいはtypeになにも指定しなければ自動でsubmitになります。なにも指定しなければ。

この記事は何? :dango:

GitHub Copilot :airplane: に頼りすぎた愚かな開発者(筆者)がHTMLの基本を忘れたことを戒めるための記事です。

起きたこと :book:

それはSvelteKitForm Actions学習中のことでした。
筆者はGitHub Copilot :airplane: を使いながら、以下のコードを作成しました。

svelte +page.svelte //.html
<script lang="ts">
	import type { ActionData } from './$types';
	export let form: ActionData;
</script>

<h1>{form}</h1>

<form method="POST">
	<button type="button">
        Click
    </button>
</form>
typescript +page.server.ts
import { error } from '@sveltejs/kit';
import type { Actions } from './$types';

export const actions: Actions = {
	default: async () => 'Hello World!'
};

(.svelteもシンタックスハイライト対応しないかな...)

ここで詳しい話は割愛いたしますが、+page.svelteformsubmitされた場合、+page.server.tsで定義したForm Actionsが実行され、画面に"Hello World!"と出力されるのが期待される動作です。

しかし実際には{form}nullのまま動きません。

解決方法 :coffee:

    <-- 下記コードを -->
	<button type="button">
        Click
    </button>
    
    <-- こうする -->
	<button>
        Click
    </button>

特に必要のない解説 :bee:

あまり説明することもないのですが、<button type="button" />と、ボタンのtypebuttonが指定されている場合、submitする能力を失ってただのボタンになっています。
そのためイベントが発火せず、Formが送信されなかったということです。

ボタンのtypeが指定されていない場合の初期値はsubmitです。form 内の button 要素を押すと submit される理由
typebuttonの場合でも、イベントハンドラーを登録することで発火させることが可能

まとめ :beach_umbrella:

GitHub Copilot :airplane: は非常に頼れる開発ツールですが、盲目的になってはいけないと再確認しました。
少なくとも、出力された結果に対してしっかり理解する姿勢が必要です。

ちなみに原因特定はChatGPT にお願いしました。
便利な世の中になったものです。いや、ほんと。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?