Created
January 18, 2022 22:26
-
-
Save AndrewIngram/54f547cd85a6fe23acd6698e825ca5f0 to your computer and use it in GitHub Desktop.
Request/Response form handling with Next.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import formidable from "formidable"; | |
export default function formData(request) { | |
const form = formidable({ multiples: true }); | |
return new Promise((resolve, reject) => { | |
form.parse(request, (err, fields, files) => { | |
if (err) { | |
reject(err); | |
return; | |
} | |
resolve({ data: fields, files }); | |
return; | |
}); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import formData from "../formData"; | |
export async function getServerSideProps({ req }) { | |
const { data } = | |
req.method === "POST" ? await formData(req) : { data: {}, errors: {} }; | |
return { | |
props: { | |
form: { | |
data, | |
}, | |
}, | |
}; | |
} | |
export default function Home({ form }) { | |
return ( | |
<main style={{ margin: "40px auto", maxWidth: "500px" }}> | |
<h1>Next.js form</h1> | |
{form.data.name ? <>Hello {form.data.name}</> : null} | |
<form action="." method="post"> | |
<label> | |
What's your name: | |
<input name="name" required autoComplete="off" /> | |
</label> | |
<button>Submit</button> | |
</form> | |
</main> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment