nextjs
  1. nextjs-forms-and-mutations

Next.js Forms and Mutations

Introduction

Forms are an integral part of any web application and are used to collect user data. Mutations, on the other hand, are used to change or update data on the server-side. Next.js provides a simple and powerful way to handle forms and mutations in your applications. In this guide, we’ll learn how to handle forms and mutations in Next.js applications.

Prerequisites

Before we begin, ensure that you have a basic understanding of React and Next.js.

Setting up the Environment

To set up the environment, make sure that you have Node.js and npm installed on your system by running the following commands in your terminal:

node -v
npm -v

If you do not have them installed, you can download and install Node.js from the official website.

Once you have Node.js and npm installed, create a new Next.js application by executing the following commands in your terminal:

npx create-next-app nextjs-forms-mutations
cd nextjs-forms-mutations

This will create a new Next.js application with the name nextjs-forms-mutations and navigate you into the project directory.

Forms in Next.js

To handle forms in Next.js, you can use the useState hook to create a state for the form data. Here’s an example of a simple form:

import { useState } from 'react';

export default function ContactForm() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    message: ''
  });

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(formData);
  }

  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormData(formData => ({
      ...formData,
      [name]: value
    }));
  }

  return (
    <form onSubmit={handleSubmit}>
      <fieldset>
        <label htmlFor="name">
          Name:
          <input
            type="text"
            id="name"
            name="name"
            value={formData.name}
            onChange={handleChange}
          />
        </label>
      </fieldset>

      <fieldset>
        <label htmlFor="email">
          Email:
          <input
            type="email"
            id="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
          />
        </label>
      </fieldset>

      <fieldset>
        <label htmlFor="message">
          Message:
          <textarea
            id="message"
            name="message"
            value={formData.message}
            onChange={handleChange}
          />
        </label>
      </fieldset>

      <button type="submit">Submit</button>
    </form>
  )
}

In this example, we’re using the useState hook to create the formData state. We then create a handleChange function that updates the formData state for each input field. Finally, we create a handleSubmit function that logs the form data to the console when the form is submitted.

Mutations in Next.js

To handle mutations in Next.js, we’ll use the useMutation hook provided by the @apollo/client library. Here’s an example of a simple mutation:

import { useMutation } from '@apollo/client';

const CREATE_POST = gql`
  mutation createPost($title: String!, $content: String!) {
    createPost(title: $title, content: $content) {
      id
      title
      content
    }
  }
`;

export default function PostForm() {
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');

  const [createPost, { loading, error }] = useMutation(CREATE_POST, {
    onCompleted: data => console.log(data),
    onError: (error) => console.log(error)
  });

  const handleSubmit = (event) => {
    event.preventDefault();
    createPost({ variables: { title, content } });
  }

  return (
    <form onSubmit={handleSubmit}>
      <fieldset>
        <label htmlFor="title">
          Title:
          <input
            type="text"
            id="title"
            name="title"
            value={title}
            onChange={e => setTitle(e.target.value)}
          />
        </label>
      </fieldset>

      <fieldset>
        <label htmlFor="content">
          Content:
          <textarea
            id="content"
            name="content"
            value={content}
            onChange={e => setContent(e.target.value)}
          />
        </label>
      </fieldset>

      <button type="submit">{ loading ? 'Loading...' : 'Create' }</button>
    </form>
  )
}

In this example, we’re using the useMutation hook to create a createPost mutation that accepts title and content as arguments. We then create a handleSubmit function that calls the createPost mutation with the title and content values. We also provide callbacks for onCompleted and onError to handle the response from the server.

Summary

In this guide, we learned how to handle forms and mutations in Next.js applications. We saw how to use the useState hook to create a state for the form data and how to use the useMutation hook to handle mutations. With this knowledge, you can now create forms and handle mutations in your Next.js applications.

Published on: