/

AI & LLM

Dec 17, 2024

Dec 17, 2024

How to write code with ChatGPT and save it as snippets

Learn techniques to use ChatGPT for coding, generate accurate code snippets, debug effectively, and create a sustainable programming workflow.

Photo of a person coding in their laptop.
Photo of a person coding in their laptop.
Photo of a person coding in their laptop.

Generative AI has changed the way we code, be it for learning how to code or for building applications. We no longer need to write everything from scratch (thanks to AI’s auto-completion powers), and also do not need to switch between multiple tabs for debugging or other coding-related queries

Don’t believe me? Well, when was the last time you looked up StackOverflow, instead of asking your co-pilot buddy?

AI can help us become a 10x dev, and for that, we need to learn:

  • How to prompt LLMs better

  • How to automate repetitive tasks with the help of AI and 

  • How to write code using ChatGPT

In this article, we will use the above mentioned tips, and show how to build a blog app with Next.js using code generated by ChatGPT and some code snippets from TinaCMS's official documentation.

Before we start building, let us understand the flow that we will follow to build the application:

Here are the prerequisites that you need to follow along with the tutorial:

We can build the blog app in five simple steps using ChatGPT and Pieces. 


Step 1: Installing Pieces to save code snippets

To smoothen our development process, we need to install Pieces, that can help us in creating the snippets as mentioned in the diagram above.

Pieces, which is an AI-enabled productivity tool, is designed to increase developer efficiency through personalized workflow assistance across the entire toolchain. You can install it by following the instructions in the documentation, which provides installation steps for Mac, Windows, and Linux operating systems.

You need to install the desktop application, browser extension, and IDE extension for Pieces.

Here’s how it will be used:

  • The desktop application will be used to create, retrieve, and transform code snippets.

  • The browser extension will be used mostly to save, copy, and share code snippets.

  • The IDE extension will be used to save, reuse, and share code snippets.


Step 2: Setting up the Next.JS application

The next step is to create a new Next.js application or use an existing Next.js application if you have one. As this tutorial shows how to use ChatGPT to write code, head over to ChatGPT and type in the prompt below:

"Show me how to initialize a Next.js application. The application should be named "tinablog" and the name of the folder should also be 'tinablog'."

The prompt above asks ChatGPT to show you how to write code for initializing a Next.js application and provides some context to guide ChatGPT, including the application and directory names.

You should get a response similar to the one in the following screenshot:

With Pieces installed, you don't have to worry about losing your code snippets from ChatGPT.

You can save a code snippet from the ChatGPT response above.

  • To do that, first enable the Pieces browser extension .

  • Then, go back to the ChatGPT chat thread, reload the page, and hover over any of the code snippets.

  • You'll see two Pieces buttons called Copy and Save and Share.

  • To save the code snippet from ChatGPT, click on the Copy and Save button. 

  • Next, open the installed Pieces desktop application to see all the code snippets you've saved.

You can see that the Pieces desktop application has automatically added each snippet with titles, descriptions, tags, and related links.

Open your terminal or command line interface and change the directory to the preferred directory where you want your Next.js application to be initialized.

Copy the code snippet titled "Next.js blog creation with npx" from Pieces and run it in your terminal.

You should also see some prompts.

For this tutorial, you can select the default answers by hitting the Enter key until the package installation starts.


Step 3: Setting up TinaCMS

The next step in building this demo blog application is to set up TinaCMS, an open-source headless CMS that supports the Markdown format.

This step is crucial, as by using this, we learn how to write code snippet in ChatGPT.

  • Go to TinaCMS's official documentation on TinaCMS and Next.js, which explains how to set up a TinaCMS blog on a Next.js application.
     

  • Save all the code snippets to Pieces, just as you did for the ChatGPT response earlier.

  • Once you've saved the code snippets on the page, launch your Pieces desktop application.

  • Then, change the directory to the Next.js application with cd tinablog and run the "TinaCMS CLI Initialization" command saved in Pieces.

  • You'll be prompted with some questions. Use the following responses:

    • When asked for your Tina Cloud Client ID, as the prompt says, you can hit Enter to set it later.

    • Select npm as your package manager.

    • Select Next.js as your framework.

    • Select "No" when asked whether you'd like to use TypeScript for your Tina configuration.


Step 4: Using ChatGPT to write code for the post listing page

In this section, we will learn how to use ChatGPT4 to write code for a page that lists all blog posts.

Enter the following ChatGPT prompts:

Show me how to add a post listing page to a Next.js and TinaCMS application.

Use the guides below:

  1. Do not create separate components or pages.

  2. Ensure you add everything in a single file.

  3. Export const getStaticProps async function that gets and returns data, query, and variables from client.queries.postConnection()

  4. Export default PostList(prop) function that gets the prop data from the returned data, query, and variables.

  5. Ensure you style the page.

The prompt above asks ChatGPT to describe how you can add a post listing page to your Next.js TinaCMS application and includes some context to guide how it should respond.

You should receive a response similar to this:

You should note that ChatGPT may not always return the exact same response, but the prompt should produce a response with a similar goal.

If you would like to continue with the exact code used in this tutorial, you can save it here.


Step 5: Using ChatGPT to debug code for the application

The final step before saving this code to Pieces is to debug and run it locally to ensure it is working as expected.

  • Change the directory to the src/pages folder of your application, create a new file called posts.js, and paste the code snippet into the newly created file.

  • After that, go back to the root directory and run the npm run dev command to compile the application.

  • You can now use ChatGPT for debugging posts.js with the following prompt:

    "There are a few errors in the code snippet you provided above. You can fix them by doing the following:
    - You should add await before client.queries.postConnection()
    - I guess there should be a postConnection before data.posts.edges. It should be something like data.posts.postConnection.edges
    - The node child should be {node.node._sys.filename} not {node.sys.filename}"


  • ChatGPT will then fix the code in response to your feedback. As mentioned before, ChatGPT might not return the same response.

    Hence, here is the link to the code snippet from the response shown in the screenshot below:

  • Copy the code snippet from the response, then replace the contents of the posts.js file with the copied code. Once you save the changes, the code should compile successfully.

  • View the page by visiting {{APPLICATION_URL}}/posts, where {{APPLICATION_URL}} is your server URL.

    In this example, it's http://localhost:3000. You can find your server URL in the compile log.

  • When you try to load the post page, you'll get a server error. This is because the data.loading variable has an undefined value, and an undefined value cannot be serialized as JSON.

  • Head back to ChatGPT to debug posts.js with the following ChatGPT prompt examples:

    "There are a few errors in the corrected code snippet you provided above. You can fix them by doing the following:
    - Remove everything that has to do with loading and error. (It should be const { data } = await client.queries.postConnection();
    - The node child should be {node.node._sys.filename} not {node.data.title}"


  • ChatGPT will again rework the code in response to your feedback. Here is the link to the code snippet shown in the screenshot below:

  • Copy the code snippet in the response, go to your posts.js file, remove the existing code in the file, and paste the code snippet you copied into posts.js.

  • Proceed to view the page by visiting {{APPLICATION_URL}}/posts.

  • Upon visiting the page, the example produces another error.

  • You will have to head back to ChatGPT to debug posts.js by providing the prompt below:
    "There are a few errors in the corrected code snippet you provided above. You can fix them by doing the following:
    - Since you are no longer returning the "post" key, data.posts.postConnection.edges.map(({ node }) should be data.postConnection.edges.map(({ node })
    - Remove the "link" tag and use "a" tag-
     The node child should be {node._sys.filename} not {node.node._sys.filename}"

The prompt above produces the following response, which you can also find ​​here.

Once again, replace the contents of the posts.js file with this updated code. Save the changes, and the code will compile.

When you view the page by visiting {{APPLICATION_URL}}/posts, it should load successfully without any errors

Before you proceed to demo the application, save the final, corrected snippet using Pieces. To do that, head back to ChatGPT, ensure you have the Pieces browser extension enabled, and use the Copy and Save button.

Pieces also provides a transform code feature. This feature enables you to make your code snippets more readable by adding inline comments and optimizing the code for better performance.

To use the code transformation feature, open the Pieces desktop app, select the snippet starting with "React Post List Component," and click the Edit icon in the upper right:

You'll be presented with the transform code interface (edit mode).

  • In edit mode, you can click the Improve Readability icon on the right side of the screen to make the code more readable.

  • Clicking the icon will apply improvements such as adding comments and making the code more legible.

  • Feel free to play around with other code transformation features in edit mode.

Also, the Pieces Copilot within the desktop application has ChatGPT and other proprietary AI models built in, which means you can code, write, save and reuse all within Pieces. 

  1. To view the blog demo, go to the TinaCMS admin page, by visiting `{{APPLICATION_URL}}/admin/index.html`

  2. Click the Enter Edit Mode button to start managing your blog application. If you want, you can add more blog posts. 

  3. To access all the blogs, go to {{APPLICATION_URL}}/posts. 

Finally, you can view an individual blog post by clicking any of the listed posts.

Final steps

If you have read this article to the end, you have not only built a blog app for yourself but also learned how to code using ChatGPT by writing prompts and using tools like Pieces to speed up the coding process.

If you are interested in this post, you'll find the other ones to your good use:

  1. Essential open source large language models to watch in 2025

  2. How to use Pieces to survive Hacktoberfest

  3. Acceptable and fast user entity resolution using dataflow

  4. Developer’s guide to LLM prompt engineering

  5. 8 Best open source AI chatbots to speed up your development process

This article was first published on September 21st, 2023, and was improved by Haimantika Mitra as of December 17th, 2024, to improve your experience and share the latest information.

Photo of the author: James Olaogun.
Photo of the author: James Olaogun.

Written by

Written by

SHARE

SHARE

How to write code with ChatGPT and save it as snippets

Title

Title

our newsletter

Sign up for The Pieces Post

Check out our monthly newsletter for curated tips & tricks, product updates, industry insights and more.

our newsletter

Sign up for The Pieces Post

Check out our monthly newsletter for curated tips & tricks, product updates, industry insights and more.

our newsletter

Sign up for The Pieces Post

Check out our monthly newsletter for curated tips & tricks, product updates, industry insights and more.