Building a Simple Task Manager with Next.js and TypeScript

Muke Johnbaptist

Muke Johnbaptist

August 24, 2024

Building a Simple Task Manager with Next.js and TypeScript

Building a Simple Task Manager with Next.js and TypeScript

Task management applications are a great way to practice building fullstack projects. In this tutorial, we'll create a simple task manager using Next.js and TypeScript.

1. Project Setup

  • Step 1: Initialize the Project
npx create-next-app@latest task-manager --typescript
cd task-manager
  • Start by creating a new Next.js project with TypeScript support.
  • Step 2: Install Dependencies
npm install axios react-query
  • Install additional libraries like axios for making HTTP requests and react-query for managing server state.

2. Creating the Task Model

  • Step 3: Define Task Type
type Task = {
  id: string;
  title: string;
  completed: boolean;
};
  • Define a Task type in a new file (e.g., types.ts) to represent the task object.

3. Building the UI

  • Step 4: Create a Task List Component
const TaskList: React.FC<{ tasks: Task[] }> = ({ tasks }) => {
  return (
    <ul>
      {tasks.map((task) => (
        <li key={task.id}>
          <span>{task.title}</span>
          <input type="checkbox" checked={task.completed} />
        </li>
      ))}
    </ul>
  );
};
  • Create a simple component to display the list of tasks.

4. Managing State with React Query

  • Step 5: Fetch Tasks
import { useQuery } from 'react-query';
import axios from 'axios';

const fetchTasks = async (): Promise<Task[]> => {
  const response = await axios.get('/api/tasks');
  return response.data;
};

const TaskManager: React.FC = () => {
  const { data: tasks, isLoading } = useQuery('tasks', fetchTasks);

  if (isLoading) return <p>Loading...</p>;

  return <TaskList tasks={tasks} />;
};
  • Use React Query to fetch tasks from an API and manage the loading state.

Conclusion

Building a task manager with Next.js and TypeScript is a practical way to learn how to structure fullstack projects, manage state, and create dynamic UIs. This tutorial covers the basics, but you can extend the application by adding features like task editing, deletion, and more.