Challenges

Create a Dashboard

Add Create Post Support

Now, we need to add the functionality to create a blog post. For that, create a file called pages/dashboard/post/create.js and add the following content:

import Theme from '../../../components/Theme'
import { useState } from 'react'
import { useRouter } from 'next/router'
import axios from 'axios'
import Link from 'next/link'

export default function CreatePost({ }) {
  const router = useRouter()
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [submitting, setSubmitting] = useState(false)

  const handleSubmit = async (e) => {
    e.preventDefault()

    try {
      setSubmitting(true)
      await axios.post('/api/post', {
        title,
        content,
        slug: title.replace(/ /g, '-')
      })
      router.push('/dashboard')
    } catch(err) {
      return alert(err.message)
    } finally {
      setSubmitting(false)
    }

    router.push('/dashboard')
  }

  return (
    <Theme>
      <div className="dashboard">
        <form className='create-post' onSubmit={handleSubmit}>
          <h2>Create New Blog Post</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>
  )
}

Here's how this page works:

  • It contains a simple form to accept content from the user.
  • Then, when the user submits the form, it'll call the handleSubmit function.
  • Inside that function, we talk to our API to create a post
  • When it completed, we will redirect the user to the /dashboard page
šŸ‘‹ If you had a closer look at the handleSubmit function, we are using a module called axios. That module helps us to call APIs with a minimum amount of code.

Before we finish this task, we need to install axios. For that invoke this command:

yarn add axios

Now, if you visit http://localhost:3009/dashboard/post/create, you can create a new blog post.


I mentioned earlier thataxios helps us to reduce the boilerplate when talking to API. So, what is the equivalent code if you are using fetch?

Option 1

const fetchRes = await fetch('/api/post', {
  method: `POST`,
  body: JSON.stringify({
    title,
    content,
    slug: title.replace(/ /g, '-')
  })
})

Option 2

const fetchRes = await fetch('/api/post', {
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title,
    content,
    slug: title.replace(/ /g, '-')
  })
})

Option 3

const fetchRes = await fetch('/api/post', {
  method: `POST`,
  headers: {
    'Content-Type': 'application/json'
  },
  body: {
    title,
    content,
    slug: title.replace(/ /g, '-')
  }
})

if (!fetchRes.ok) {
  throw new Error(await fetchRes.text())
}

Option 4

const fetchRes = await fetch('/api/post', {
  method: `POST`,
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title,
    content,
    slug: title.replace(/ /g, '-')
  })
})

if (!fetchRes.ok) {
  throw new Error(await fetchRes.text())
}
Q: Select the correct option?
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: