Web Developers : 14-Build a Dynamic Shop Page in Next.js to Add Products Using Apollo useMutation
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.
Install Apollo Client and GraphQL:
Run the following command in your terminal:
npm install @apollo/client graphqlCreate Apollo Client:
Create a new file named
apollo-client.jsin 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;Wrap Your Application:
Modify your
_app.jsfile to wrap your application withApolloProvider:// 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.
Create a New Page:
Create a new file called
shop.jsin thepagesdirectory:// 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_PRODUCTusing thegqltemplate literal. This mutation takesnameandpriceas parameters and returns the newly added product'sid,name, andprice.useMutation Hook: We utilize the
useMutationhook from Apollo Client to execute the mutation. TheaddProductfunction will trigger the mutation when called.Form Submission: We handle the form submission with the
handleAddProductfunction. It prevents the default form submission behavior, gathers the input values, and calls theaddProductmutation 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!
Connect with SkillBakery Studios
Explore more tutorials, tools, and resources:
Posted by SkillBakery Studios


No comments:
Post a Comment