h-yabi2 / Next.js-MongoDB-TodoAPP

App Router, Server Actions, MongoDB学習
0 stars 0 forks source link

タスク一覧取得のAPI作成、取得、表示 #3

Open h-yabi2 opened 3 weeks ago

h-yabi2 commented 3 weeks ago

API 作成

src/app/api/tasks/route.ts

import { TaskDocument, TaskModel } from "@/models/task";
import { connectDB } from "@/utils/database";
import { NextResponse } from "next/server";

export const GET = async () => {
  try {
    await connectDB();
    const allTasks: TaskDocument[] = await TaskModel.find();
    console.log(allTasks);

    return NextResponse.json({
      message: "タスク一覧を取得しました",
      tasks: allTasks,
    });
  } catch (error) {
    console.log(error);
    return NextResponse.json({
      message: "タスク一覧の取得に失敗しました",
      status: 500,
    });
  }
};

export const dynamic = "force-dynamic";
h-yabi2 commented 3 weeks ago

API確認

スクリーンショット 2024-10-27 11 54 21
h-yabi2 commented 3 weeks ago

API取得コード

.env

src/app/(main)/page.tsx


const getAllTasks = async (): Promise<TaskDocument[]> => { const response = await fetch(${process.env.API_URL}/tasks, { cache: "no-store", }); if (response.status !== 200) { throw new Error("Failed to fetch tasks"); } const data = await response.json(); return data.tasks as TaskDocument[]; };


export default async function MainPage() { const allTasks = await getAllTasks(); ~

h-yabi2 commented 3 weeks ago

実際に表示するコード