実現したいこと
Edit機能がちゃんとできるようになりたい
発生している問題・分からないこと
Editを押すと404notfoundになる。
エラーメッセージ
error
1404notfound
該当のソースコード
rails
1/backend/app/controllers/todos_controller.rb 2 3class TodosController < ApplicationController 4 5 def index 6 # 日付が新しい順に10件まで取得する 7 @todos = Todo.all.order(created_at: :desc).limit(10) 8 9 render json: @todos 10 11 end 12 13 def show 14 15 @todo = Todo.find(params[:id]) 16 17 render json: @todo 18 end 19 20 def create 21 22 @todo = Todo.new(todo_params) 23 24 if @todo.save 25 render json: @todo, status: :created, location: @todo 26 else 27 render json: @todo.errors, status: :unprocessable_entity 28 end 29 end 30 31 def update 32 @todo = Todo.find(params[:id]) 33 34 if @todo.update(todo_params) 35 render json: @todo 36 else 37 render json: @todo.errors, status: :unprocessable_entity 38 end 39 end 40 41 def todo_params 42 params.require(:todo).permit(:title, :content) 43 end 44end 45
next.js
1/frontend/app/components/EditTodoForm.tsx 2 3"use client"; 4 5import React, { useState } from 'react'; 6import { useRouter } from 'next/navigation'; 7import axios from 'axios'; 8import useSWR from 'swr'; 9 10type EditTodoFormProps = { 11 id: number; 12}; 13 14const fetcher = (url: string) => axios.get(url).then(res => res.data); 15 16const EditTodoForm = ({ id }: EditTodoFormProps) => { 17 const router = useRouter(); 18 const [title, setTitle] = useState(''); 19 const [content, setContent] = useState(''); 20 const [error, setError] = useState(''); 21 22 const { data, error: fetchError } = useSWR(id ? `http://localhost:3000/todos/${id}` : null, fetcher); 23 24 // Set initial form values when data is loaded 25 React.useEffect(() => { 26 if (data) { 27 setTitle(data.title); 28 setContent(data.content); 29 } 30 }, [data]); 31 32 const handleSubmit = async (e: React.FormEvent) => { 33 e.preventDefault(); 34 35 if (!title || !content) { 36 setError('Title and content are required'); 37 return; 38 } 39 40 try { 41 await axios.put(`http://localhost:3000/todos/${id}`, { todo: { title, content } }); 42 router.push(`/todos/${id}`); 43 } catch (error) { 44 setError('Failed to update todo'); 45 console.error(error); 46 } 47 }; 48 49 if (fetchError) return <div>Failed to load todo</div>; 50 if (!data) return <div>Loading...</div>; 51 52 return ( 53 <div className="space-y-6 py-16"> 54 <form onSubmit={handleSubmit} className="space-y-6"> 55 <label className="block text-xl font-bold text-gray-700">Edit Todo</label> 56 <input 57 type="text" 58 value={title} 59 onChange={(e) => setTitle(e.target.value)} 60 placeholder="タイトル" 61 className="block w-full py-2 pl-3 pr-4 text-base border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-gray-500 focus:border-gray-500 sm:text-sm" 62 /> 63 <textarea 64 value={content} 65 onChange={(e) => setContent(e.target.value)} 66 placeholder="本文" 67 className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-gray-500 focus:border-gray-500 sm:text-sm" 68 /> 69 {error && <p className="text-red-500">{error}</p>} 70 <button 71 type="submit" 72 className="mt-3 ml-auto flex justify-center py-2 px-8 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500" 73 > 74 Update 75 </button> 76 </form> 77 </div> 78 ); 79}; 80 81export default EditTodoForm; 82 83
next.js
1/frontend/app/app/todos/[id]/edit.tsx 2 3"use client"; 4 5import { useRouter } from 'next/navigation'; 6import Link from 'next/link'; 7import EditTodoForm from '@/components/EditTodoForm'; 8import useSWR from 'swr'; 9 10 const EditTodoPage = ({ params }: { params: { id: string } }) => { 11 const router = useRouter(); 12 const { id } = params; 13 // SWR を使ってクエリパラメータがあるか確認します 14 const { data: todoId, error } = useSWR( 15 id ? `/todos/${id}` : null, 16 () => parseInt(id as string) 17 ); 18 19 if (error) return <div>Failed to load the page</div>; 20 if (!todoId) return <div>Loading...</div>; 21 22 return ( 23 <div className="flex justify-center items-center"> 24 <div className="flex flex-col w-3/4 max-w-lg"> 25 <EditTodoForm id={todoId} /> 26 <Link 27 href="/" 28 className="ml-auto font-medium text-blue-600 hover:bg-blue-300 focus:outline-none" 29 > 30 Back 31 </Link> 32 </div> 33 </div> 34 ); 35}; 36 37export default EditTodoPage; 38
/frontend/app/app/todos/[id]/page.tsx "use client"; import { useEffect, useState } from 'react'; import { useRouter } from 'next/navigation'; import useSWR from 'swr'; import Link from 'next/link'; import Todo from '@/components/Todo'; import { TodoType } from '@/types/Todo'; import axios from 'axios'; // Fetcher function for SWR const fetcher = (url: string) => axios.get(url).then(res => res.data); // Todo詳細ページを表示するコンポーネント const TodoDetail = ({ params }: { params: { id: string } }) => { // ルーティング情報を取得する const router = useRouter(); const { id } = params; // SWRを使ってデータを取得する const { data: todo, error } = useSWR<TodoType>(id ? `http://localhost:3000/todos/${id}` : null, fetcher); // エラーが発生した場合の処理 if (error) return <div>Failed to load</div>; // Todoを取得中の場合は「Loading...」を表示する if (!todo) return <div>Loading...</div>; return ( <div className="flex justify-center items-center"> <div className="flex flex-col space-y-6 w-3/4 max-w-lg pt-10"> <label className="block text-xl font-bold text-gray-700">Todo</label> <div> <h2 className="text-2xl font-semibold">{todo.title}</h2> <p className="mt-2 text-gray-600">{todo.content}</p> </div> <div className="flex justify-end"> <Link href={`/todos/${id}/edit`} className="mt-auto font-medium text-blue-600 hover:bg-blue-300 focus:outline-none mr-12" > Edit </Link> <Link href="/" className="mt-auto font-medium text-blue-600 hover:bg-blue-300 focus:outline-none" > Back </Link> </div> </div> </div> ); }; export default TodoDetail;
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
自分で試したこと
import { useRouter } from 'next/router'→import { useRouter } from 'next/navigation';
修正
const EditTodoPage = ({ params }: { params: { id: string } }) => { const router = useRouter(); const { id } = params;
に書き換えた。
補足
tree構造
|-- README.md |-- app | |-- favicon.ico | |-- globals.css | |-- layout.tsx | |-- page.tsx | `-- todos |-- components | |-- CreateTodoForm.tsx | |-- EditTodoForm.tsx | |-- Todo.tsx | `-- Todos.tsx |-- next-env.d.ts |-- next.config.mjs |-- node_modules
回答1件
あなたの回答
tips
プレビュー