Building a Simple Bulletin Board App with Next.js and ChatGPT

Published: Saturday, March 18, 2023 Tags: 4
Authors

This article walks through building a simple bulletin board app with React, TypeScript, and Next.js, while using ChatGPT as a drafting assistant.

Prompt Used for Drafting

Write a technical article with the given theme, technologies, and outline.
Use Markdown format.

Theme
- How to build a bulletin board app with Next.js

Technologies
- React
- TypeScript
- Next.js

Rules
- Use up-to-date techniques where possible
- Include many code examples
- Explain the code clearly

Environment Setup

npm create-next-app bulletin-app
npm install react react-dom next typescript

Frontend

Create reusable components such as MessageList, and wire them into pages/index.tsx.

import React, { useState } from "react";

const HomePage: React.FC = () => {
  const [messages, setMessages] = useState<string[]>([]);

  const handleFormSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const formData = new FormData(event.currentTarget);
    const message = formData.get("message") as string;
    setMessages((prev) => [...prev, message]);
  };

  return (
    <div>
      <form onSubmit={handleFormSubmit}>
        <input name="message" type="text" />
        <button type="submit">Post Message</button>
      </form>
      <ul>
        {messages.map((message) => (
          <li key={message}>{message}</li>
        ))}
      </ul>
    </div>
  );
};

export default HomePage;

API Layer

Implement GET and POST handlers to read and append messages.

let messages: string[] = [];

export const getMessages = (): string[] => messages;

export const addMessage = (message: string): void => {
  messages.push(message);
};

Persistence with PostgreSQL

Install packages and configure a connection string.

npm install pg
npm install --save-dev @types/pg
DATABASE_URL=postgresql://postgres:password@localhost:5432/nextjs_board
import { Pool } from "pg";

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  ssl: process.env.NODE_ENV === "production",
});

export const query = (text: string, params?: unknown[]) => {
  return pool.query(text, params);
};

Integrating Frontend and Backend

On page load, fetch messages. On submit, post a message and refetch the latest list.

Conclusion

The project shows a complete vertical slice: UI, API, and database persistence. This is a strong foundation for adding authentication, moderation, pagination, and richer message metadata.

Related Articles

Ranked by shared tags and recency of publication date.

Shared tags: Next.js, React, TypeScript, ChatGPT

How to Build a Todo App with Next.js

A practical walkthrough for building a Todo app using React, TypeScript, and Next.js.

Mar 17, 2023

Recent post

Hello World.

Hello World. A short introduction to this site and what I will share here.

Feb 23, 2023