Home
...
````
You can use `fetch` to send the data to the API route we created earlier, but I prefer axios.
Install axios:
```bash
yarn add axios
```
Update the handle submit function to use axios:
```js
import axios from 'axios'
...
const handleSubmit = async (e) => {
e.preventDefault()
const res = await axios.post('/api/posts', { title, content })
console.log(res.data)
}
````
```ts
import axios from 'axios'
...
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
const res = await axios.post('/api/posts', { title, content })
console.log(res.data)
}
````
Now when you submit the form, you should see the new post in the console. You can also check the past is created using Prisma Studio.
But when a new post is created, the home page doesn't update. We need to refresh to see the new post appear on the page. Let's fix this using `useState`.
`useState` to keep track of the newly created posts:
```js
const [posts, setPosts] = useState(props.posts)
// Add a use effect in case the posts change when routing to the home page
useEffect(() => {
setPosts(props.posts)
}, [props.posts])
const handleSubmit = async (e) => {
e.preventDefault()
const res = await axios.post('/api/posts', { title, content })
setPosts([...posts, res.data])
}
````
```ts
const [posts, setPosts] = useState(props.posts)
// Add a use effect in case the posts change when routing to the home page
useEffect(() => {
setPosts(props.posts)
}, [props.posts])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
const res = await axios.post('/api/posts', { title, content })
setPosts([...posts, res.data])
}
````
Make sure you import `useEffect` for this to work. Try submitting a new post again and you should see it appear on the page without having to refresh.
## Where to go from here
This is a pretty basic app, but it's a good starting point for next and prisma. Go build an app now and refer to the prisma docs when you're unsure about how to do something. Here are some useful links:
- [Crud](https://www.prisma.io/docs/concepts/components/prisma-client/crud)
- [Seeding your database](https://www.prisma.io/docs/guides/database/seed-database)
- [Get started with Prisma Migrate](https://www.prisma.io/docs/concepts/components/prisma-migrate/get-started)
---
## Code
[https://github.com/Sam-Meech-Ward/code_snippets_prisma_next_demo.git](https://github.com/Sam-Meech-Ward/code_snippets_prisma_next_demo.git)
**schema.prisma**
```prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Post {
id Int @id @default(autoincrement())
title String
code String @db.Text
language String
totalLikes Int @default(0)
totalComments Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
```
**server/db/client.js**
```js
import { PrismaClient } from "@prisma/client"
export const prisma = global.prisma || new PrismaClient()
if (process.env.NODE_ENV !== "production") global.prisma = prisma
```
**pages/api/posts.js**
```js
import { prisma } from "../../server/db/client"
function titleFromCode(code) {
return code.trim().split("\n")[0].replace("// ", "")
}
export default async function handler(req, res) {
const { method } = req
switch (method) {
case "POST":
const { language, code } = req.body
const title = titleFromCode(code)
const post = await prisma.post.create({
data: {
title,
language,
code,
},
})
res.status(201).json(post)
break
default:
res.setHeader("Allow", ["POST"])
res.status(405).end(`Method ${method} Not Allowed`)
}
}
```
**pages/index.js**
```js
import { prisma } from "../server/db/client"
import PostSmall from "../components/PostSmall"
import Button from "../components/Button"
export default function Home({ posts }) {
return (
<>
{posts?.map((post) => (
-
))}
>
)
}
export async function getServerSideProps() {
// will always run on the server
// newest first
const posts = await prisma.post.findMany({
orderBy: {
createdAt: "desc",
},
})
return {
props: {
posts: JSON.parse(JSON.stringify(posts)),
},
}
}
```