Memo

メモ > 技術 > フレームワーク: Next.js > サーバアクション

サーバアクション
src/app/public/sample.json
{ "message":"これはデータのサンプルです。", "data":[ {"name":"太郎","mail":"taro@example.com","age":"39"}, {"name":"花子","mail":"hanako@example.com","age":"28"}, {"name":"幸子","mail":"sachico@example.com","age":"17"} ] }
src/app/action/page.tsx
'use client' import { getSampleData } from './get-sample-data' export default async function Action() { return ( <main> <h1 className="title">Action sample</h1> <p className="message">ボタンをクリックしてください。</p> <form className="m-5" action={getSampleData}> <input type="number" className="input" name="number" /> <button className="button">クリック</button> </form> </main> ) }
src/app/action/get-sample-data.tsx
'use server' import { redirect } from 'next/navigation' export async function getSampleData(form) { const number = form.get('number') const resp = await fetch( 'http://localhost:3000/sample.json', { cache: 'no-store' } ) const result = await resp.json() console.log(number) let data = result.data[number] if (data == null) { data = {name:'-',mail:'-',age:0} } const query = 'name=' + data.name + '&mail=' + data.mail + '&age=' + data.age const searchParams = new URLSearchParams(query) redirect('/action-result?' + searchParams.toString()) }
src/app/action-result/page.tsx
'use client' import Link from 'next/Link' import { useSearchParams } from 'next/navigation' export default async function ActionResult() { const params = useSearchParams() return ( <main> <h1 className="title">Action sample</h1> <p className="message">以下のデータを取得しました。</p> <ul className="m-5"> <li>name: {params.get('name')}</li> <li>mail: {params.get('mail')}</li> <li>age: {params.get('age')}</li> </ul> <div className="m-5"> <Link href="/action" className="text-blue-600 underline">戻る</Link> </div> </main> ) }

Advertisement