Challenges

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) => {
    e.preventDefault()
    
    try {
      setSubmitting(true)
      await axios.patch(`/api/post?slug=${encodeURIComponent(post.slug)}`, {
        title,
        content
      })
      router.push('/dashboard')
    } catch(err) {
      return alert(err.message)
    } finally {
      setSubmitting(false)
    }
  }

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

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

  return {
    props: {
      post
    }
  }
}

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 axios.post. 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?
authenticating...

šŸ™ We need your help

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