diff --git a/src/pages/posts/new.jsx b/src/pages/posts/new.jsx new file mode 100644 index 0000000..d86ea74 --- /dev/null +++ b/src/pages/posts/new.jsx @@ -0,0 +1,82 @@ +import { useState } from "react"; +import { useRouter } from "next/router"; + +export default function NewPost() { + // track form fields + const [title, setTitle] = useState(""); + const [body, setBody] = useState(""); + + // store any errors from the server + const [errors, setErrors] = useState([]); + + // next.js router to redirect after form submits + const router = useRouter(); + + // handle the form submit + const handleSubmit = async (e) => { + // stop page from refreshing + e.preventDefault(); + + // clear any old errors + setErrors([]); + + // send post request to api + const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/posts`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ title, body }), + }); + + // if work go back home + if (res.status === 201) { + router.push("/"); + } else { + // if error show on form + const data = await res.json(); + setErrors(data.errors || ["something wrong"]); + } + }; + + return ( +