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?

microCMSで記事を最新の10件だけ取得する方法

Last updated at Posted at 2025-03-31

microCMSの管理画面ではこちらで取得したい値を設定し取得ボタンをクリックし
意図した値が返ってきているか確認する。

スクリーンショット 2025-03-31 22.34.44.png


取得結果が必要とする最新のデータが10件表示されていればOK

{
    "contents": [
        {
            "id": "aaaaaa",
            "title": "記事1"
        },
        {
            "id": "bbbbb",
            "title": "記事2"
        },
        {
            "id": "cccc",
            "title": "記事3"
        },
        {
            "id": "dddd",
            "title": "記事4"
        },
        {
            "id": "eeeee",
            "title": "記事5"
        },
        {
            "id": "fffff",
            "title": "記事6"
        },
        {
            "id": "gggggg",
            "title": "記事7"
        },
        {
            "id": "hhhh",
            "title": "記事8"
        },
        {
            "id": "iiiii",
            "title": "記事9"
        },
        {
            "id": "jjjjj",
            "title": "記事10"
        },

    ],
    "totalCount": 17,
    "offset": 0,
    "limit": 10
}

意図した値が返ってきていたらOK!

任意のファイルにコードを記述する

libs/microcms.ts
// 最新の記事一覧を取得
export async function getLatestPost() {
  const latestPosts = await client.get({
    endpoint: "blog",
    queries: { limit: 10, orders: "-createdAt", fields: "title,id" },
  });

  return latestPosts; 
}

タイトル一覧を表示させ、id をslugで運用しているのでこのようなコンポーネントにしました。

components/LatestPostList.tsx
import Link from "next/link";
import React from "react";

interface PostList {
  postTitle: string;
  postSlug: string;
}

export default function PostList({ postTitle, postSlug }: PostList) {
  return (
    <>
      <Link
        href={`/blog/${postSlug}`}
        className="block pt-3 indent-2 text-sm hover:text-gray-400"
      >
        {postTitle}
      </Link>
    </>
  );
}

これで最新の10件のタイトルとそれに紐付く記事のリンクが作成され
遷移できます。

src/app/page.tsx
// 最新の記事の10件を表示
{latestPosts.contents.map(
(latestPost: { id: string; title: string }) => (
  <PostList
    key={latestPost.id}
    postTitle={latestPost.title}
    postSlug={latestPost.id}
  />
)
)}

方法は色々模索中なのでよりベターな方法があれば
教えていただけるとうれしいです!!

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?