Web Developers : 14-Build a Dynamic Shop Page in Next.js to Add Products Using Apollo useMutation - SkillBakery Studios

Breaking

Post Top Ad

Post Top Ad

Sunday, July 19, 2026

Web Developers : 14-Build a Dynamic Shop Page in Next.js to Add Products Using Apollo useMutation

Web Developers : 14-Build a Dynamic Shop Page in Next.js to Add Products Using Apollo useMutation

Screenshot from the tutorial
Screenshot from the tutorial

Building a Dynamic Shop Page in Next.js with Apollo useMutation

In this tutorial, we'll dive into the world of Next.js and Apollo Client to create a dynamic shop page where users can add products effortlessly. This step-by-step guide will help you understand how to leverage the power of GraphQL mutations with Apollo's useMutation hook in a Next.js environment.

Prerequisites

Before we begin, ensure that you have the following set up:

  • Basic knowledge of React and JavaScript.
  • Node.js and npm installed on your machine.
  • A Next.js project initialized (you can create one using npx create-next-app).
  • Apollo Client and GraphQL set up in your Next.js app.

Setting Up Apollo Client

First, you need to set up Apollo Client to connect your Next.js application to a GraphQL API.

  1. Install Apollo Client and GraphQL:

    Run the following command in your terminal:

    npm install @apollo/client graphql
    
  2. Create Apollo Client:

    Create a new file named apollo-client.js in the root of your project:

    // apollo-client.js
    import { ApolloClient, InMemoryCache } from '@apollo/client';
    
    const client = new ApolloClient({
      uri: 'https://your-graphql-endpoint.com/graphql', // replace with your GraphQL endpoint
      cache: new InMemoryCache(),
    });
    
    export default client;
    
  3. Wrap Your Application:

    Modify your _app.js file to wrap your application with ApolloProvider:

    // pages/_app.js
    import { ApolloProvider } from '@apollo/client';
    import client from '../apollo-client';
    
    function MyApp({ Component, pageProps }) {
      return (
        <ApolloProvider client={client}>
          <Component {...pageProps} />
        </ApolloProvider>
      );
    }
    
    export default MyApp;
    

Creating the Dynamic Shop Page

Let's create a new page where users can add products to the shop.

  1. Create a New Page:

    Create a new file called shop.js in the pages directory:

    // pages/shop.js
    import { useMutation } from '@apollo/client';
    import gql from 'graphql-tag';
    
    const ADD_PRODUCT = gql`
      mutation AddProduct($name: String!, $price: Float!) {
        addProduct(name: $name, price: $price) {
          id
          name
          price
        }
      }
    `;
    
    const Shop = () => {
      const [addProduct] = useMutation(ADD_PRODUCT);
    
      const handleAddProduct = async (event) => {
        event.preventDefault();
        const { name, price } = event.target.elements;
    
        try {
          await addProduct({
            variables: {
              name: name.value,
              price: parseFloat(price.value),
            },
          });
          alert('Product added successfully!');
          event.target.reset();
        } catch (error) {
          console.error('Error adding product:', error);
        }
      };
    
      return (
        <div>
          <h1>Shop Page</h1>
          <form onSubmit={handleAddProduct}>
            <input type="text" name="name" placeholder="Product Name" required />
            <input type="number" name="price" placeholder="Product Price" required />
            <button type="submit">Add Product</button>
          </form>
        </div>
      );
    };
    
    export default Shop;
    

Explanation of the Code

  • GraphQL Mutation: We define a GraphQL mutation ADD_PRODUCT using the gql template literal. This mutation takes name and price as parameters and returns the newly added product's id, name, and price.

  • useMutation Hook: We utilize the useMutation hook from Apollo Client to execute the mutation. The addProduct function will trigger the mutation when called.

  • Form Submission: We handle the form submission with the handleAddProduct function. It prevents the default form submission behavior, gathers the input values, and calls the addProduct mutation with the gathered data.

Styling the Shop Page

To enhance the user experience, consider adding some basic CSS styles. You can create a separate CSS file or use inline styles. Here’s a simple example using inline styles:

// Add this inside the Shop component
const formStyle = {
  display: 'flex',
  flexDirection: 'column',
  width: '300px',
  margin: 'auto',
};

return (
  <div>
    <h1>Shop Page</h1>
    <form onSubmit={handleAddProduct} style={formStyle}>
      <input type="text" name="name" placeholder="Product Name" required />
      <input type="number" name="price" placeholder="Product Price" required />
      <button type="submit">Add Product</button>
    </form>
  </div>
);

Conclusion

Congratulations! You have successfully built a dynamic shop page in Next.js that allows users to add products using Apollo Client's useMutation hook. This tutorial covered the essentials of setting up Apollo, creating a GraphQL mutation, and integrating it with a Next.js application.

Feel free to expand upon this project by adding features like displaying the list of products, editing, or deleting them. Happy coding!

Another screenshot from the tutorial
Another view from the tutorial

Connect with SkillBakery Studios

Explore more tutorials, tools, and resources:

Posted by SkillBakery Studios

No comments:

Post a Comment

Post Top Ad