実現したいこと
詳細ページを作って表示させたい。
発生している問題・分からないこと
Unhandled Runtime Error
TypeError: Cannot destructure property 'id' of 'router.query' as it is undefined.
Source
app/todos/[id]/page.tsx (18:11) @ id
16 | // ルーティング情報を取得する
17 | const router = useRouter();
18 | const { id } = router.query;
| ^
19 |
20 | // SWRを使ってデータを取得する
21 | const { data: todo, error } = useSWR<TodoType>(id ?http://localhost:3000/todos/${id}
: null,
どうしたらいいかわからない。
エラーメッセージ
Unhandled Runtime Error
TypeError: Cannot destructure property 'id' of 'router.query' as it is undefined.
Source
app/todos/[id]/page.tsx (18:11) @ id
16 | // ルーティング情報を取得する
17 | const router = useRouter();
18 | const { id } = router.query;
| ^
19 |
20 | // SWRを使ってデータを取得する
21 | const { data: todo, error } = useSWR<TodoType>(id ?http://localhost:3000/todos/${id}
: null,
該当のソースコード
rails
1class TodosController < ApplicationController 2 3 def index 4 # 日付が新しい順に10件まで取得する 5 @todos = Todo.all.order(created_at: :desc).limit(10) 6 7 render json: @todos 8 9 end 10 11 def show 12 @todo = Todo.find(params[:id]) 13 14 render json: @todo 15 end 16
TYpescript
1"use client"; 2 3import { useEffect, useState } from 'react'; 4import { useRouter } from 'next/navigation'; 5import useSWR from 'swr'; 6import Link from 'next/link'; 7import Todo from '@/components/Todo'; 8import { TodoType } from '@/types/Todo'; 9import axios from 'axios'; 10 11// Fetcher function for SWR 12const fetcher = (url: string) => axios.get(url).then(res => res.data); 13 14// Todo詳細ページを表示するコンポーネント 15const TodoDetail = () => { 16 // ルーティング情報を取得する 17 const router = useRouter(); 18 const { id } = router.query; 19 20 // SWRを使ってデータを取得する 21 const { data: todo, error } = useSWR<TodoType>(id ? `http://localhost:3000/todos/${id}` : null, fetcher); 22 23 // エラーが発生した場合の処理 24 if (error) return <div>Failed to load</div>; 25 26 // Todoを取得中の場合は「Loading...」を表示する 27 if (!todo) return <div>Loading...</div>; 28 29 return ( 30 <div className="flex justify-center items-center"> 31 <div className="flex flex-col space-y-6 w-3/4 max-w-lg pt-10"> 32 <label className="block text-xl font-bold text-gray-700">Todo</label> 33 <Todo todo={todo} /> 34 <div className="flex justify-end"> 35 <Link 36 href="/" 37 className="mt-auto font-medium text-blue-600 hover:bg-blue-300 focus:outline-none" 38 > 39 Back 40 </Link> 41 </div> 42 </div> 43 </div> 44 ); 45}; 46 47export default TodoDetail; 48
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
import { useRouter } from 'next/navigation';
に変えた
補足
特になし

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。