Create a Dashboard

Add Edit Post Support

Usually, we need a way to edit our blog posts. So, let's implement that functionality.

To do that, create a file called pages/dashboard/post/[slug].js and add the following content:

import Theme from '../../../components/Theme'
import { getPost } from '../../../lib/data'
import { useRouter } from 'next/router'
import { getSession } from 'next-auth/client'
import { useState } from 'react'
import axios from 'axios'

export default function EditPost({ post }) {
  const [title, setTitle] = useState(post && post.title)
  const [content, setContent] = useState(post && post.content)
  const [submitting, setSubmitting] = useState(false)
  const router = useRouter()

  const handleSubmit = async (e) => {
    try {
      await axios.patch(`/api/post?slug=${encodeURIComponent(post.slug)}`, {
    } catch(err) {
      return alert(err.message)
    } finally {

  return (
      <div className="dashboard">
        <form className='edit-post' onSubmit={handleSubmit}>
          <h2>Edit: {post.title}</h2>
            placeholder="Add your blog post title"
            onChange={e => setTitle(}
            placeholder="Add your blog post content"
            onChange={e => setContent(}
          <button disabled={submitting}>
            {submitting? 'submitting ...' : 'Submit'}

export async function getServerSideProps({ req, params }) {
  const session = await getSession({ req })
  const post = await getPost(params.slug, { ownerId: })

  return {
    props: {

If you look at the codebase, this is very similar to what we did in the previous step. Here are the major differences:

  • We are using getServerSideProps to get the related post object
  • We also use axios.patch instead of That's because we update a blog post in this case.

Run your app with these changes, and try to edit some blog posts.

Now here's a little experiment for you:

  • Log in to our app and visit the dashboard
  • Create a blog post if there's no such post
  • Go to the edit post page
  • Now click "Logout"
Q: What was the outcome?

šŸ™ We need your help

We need your help to keep maintain & add new content to this course. Here's how you can support us: