🦁
Nextjs×Prisma×SQLiteでreadする方法(その1)
findManyで全データを取得する。
./pages/index
import prisma from "@utils/prisma"
type post = {
id:number,
title:string,
content:string,
published:boolean
}
export default function Home({posts}:{posts:post[]}) {
return(
<ul>
{
posts.map((post:post)=>(
<li key={post.id}>
<p>{post.id}</p>
<p>{post.title}</p>
<p>{post.content}</p>
<p>{post.published}</p>
</li>
))
}
</ul>
)
}
export async function getServerSideProps() {
const posts = await prisma.post.findMany()
return {
props: {
posts:posts,
}
}
}
getServerSidePropsのところでfindManyを使って全データを取得しています。
export async function getServerSideProps() {
const posts = await prisma.post.findMany()
return {
props: {
posts:posts,
}
}
}
postの型を定義しています。
type post = {
id:number,
title:string,
content:string,
published:boolean
}
mapを使ってpostsの中身をpostに順番に入れてid,title,content,publishedを表示させています。
export default function Home({posts}:{posts:post[]}) {
return(
<ul>
{
posts.map((post:post)=>(
<li key={post.id}>
<p>{post.id}</p>
<p>{post.title}</p>
<p>{post.content}</p>
<p>{post.published}</p>
</li>
))
}
</ul>
)
}
ブラウザで確認すると全データ取得できています。
readは簡単でしたね。次は1件だけデータをreadしてみようと思います。
Discussion