Task Management application

Frontend (React.js)

App.js

This component serves as the main entry point for our application. It manages the state of the user and tasks, fetches data from the backend on component mount, and provides handlers for task creation and deletion.

  • useEffect: This React Hook is used for performing side effects in functional components. In this case, it fetches the current user and tasks from the backend when the component mounts.
  • handleTaskSubmit: This function is called when the user submits the task form. It sends the task data to the backend for creation and updates the local state with the new task.
  • handleTaskDelete: This function is called when the user deletes a task. It sends a request to the backend to delete the task by its ID and updates the local state to reflect the deletion.

TaskForm.js

This component renders a form for creating new tasks. It manages the state of the task title and description inputs and provides a submit handler to the parent component.

  • useState: This React Hook is used for managing state in functional components. It initializes state variables for the task title and description inputs.
  • handleSubmit: This function is called when the user submits the form. It collects the input values, calls the submit handler passed from the parent component, and clears the input fields.

TaskList.js

This component renders a list of tasks. It receives an array of tasks as props from the parent component and provides a delete button for each task.

  • map: This JavaScript array method is used to iterate over the tasks array and generate a list item for each task.
  • onDelete: This function is called when the user clicks the delete button for a task. It calls the delete handler passed from the parent component with the task ID as an argument.

services/AuthService.js and services/TaskService.js

These files contain service modules for handling authentication and task-related operations, respectively. They provide methods for interacting with the backend API and returning promises for asynchronous operations.

  • getCurrentUser: This method fetches the current user from the backend. In a real application, it would make an HTTP request to the server and return the user data.
  • getTasks: This method fetches a list of tasks from the backend. Similarly, it would make an HTTP request to the server and return the task data.
  • createTask and deleteTask: These methods send POST and DELETE requests to the backend, respectively, to create and delete tasks. They would include logic for interacting with the backend API endpoints.

Backend (Node.js + Express)

server.js

This file sets up a basic Express server to handle HTTP requests for fetching, creating, and deleting tasks.

  • app.get('/tasks'): This route handler responds to GET requests to the /tasks endpoint by sending the list of tasks stored in the tasks array as JSON.
  • app.post('/tasks'): This route handler responds to POST requests to the /tasks endpoint by creating a new task with the data provided in the request body. It adds the new task to the tasks array and sends it back as JSON with a status code of 201 (Created).
  • app.delete('/tasks/:id'): This route handler responds to DELETE requests to the /tasks/:id endpoint by deleting the task with the specified ID from the tasks array. It sends a status code of 204 (No Content) to indicate successful deletion.

Running the Application

To run the application:

  1. Navigate to the project directory containing the frontend and backend folders.
  2. Run npm install in both the frontend and backend folders to install dependencies.
  3. Run npm start in both folders to start the frontend and backend servers.
  4. Open your browser and navigate to http://localhost:3000 to view the application.

This setup provides a basic foundation for a task management application with frontend and backend components. You can further expand and customize it by adding features such as user authentication, real-time updates, database integration, error handling, and more, depending on your requirements.

Let’s start with the frontend code:

Frontend (React.js)

App.js

jsx

import React, { useEffect, useState } from 'react';
import TaskList from './components/TaskList';
import TaskForm from './components/TaskForm';
import AuthService from './services/AuthService';
import TaskService from './services/TaskService';

const App = () => {
const [user, setUser] = useState(null);
const [tasks, setTasks] = useState([]);

useEffect(() => {
const fetchUser = async () => {
try {
const user = await AuthService.getCurrentUser();
setUser(user);
} catch (error) {
console.error('Error fetching user:', error);
}
};

const fetchTasks = async () => {
try {
const tasks = await TaskService.getTasks();
setTasks(tasks);
} catch (error) {
console.error('Error fetching tasks:', error);
}
};

fetchUser();
fetchTasks();
}, []);

const handleTaskSubmit = async (taskData) => {
try {
const newTask = await TaskService.createTask(taskData);
setTasks([...tasks, newTask]);
} catch (error) {
console.error('Error creating task:', error);
}
};

const handleTaskDelete = async (taskId) => {
try {
await TaskService.deleteTask(taskId);
setTasks(tasks.filter(task => task._id !== taskId));
} catch (error) {
console.error('Error deleting task:', error);
}
};

return (
<div>
<h1>TaskMaster</h1>
<h2>Welcome, {user ? user.username : 'Guest'}</h2>
<TaskForm onSubmit={handleTaskSubmit} />
<TaskList tasks={tasks} onDelete={handleTaskDelete} />
</div>
);
};

export default App;

TaskForm.js

jsx

import React, { useState } from 'react';

const TaskForm = ({ onSubmit }) => {
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');

const handleSubmit = (e) => {
e.preventDefault();
onSubmit({ title, description });
setTitle('');
setDescription('');
};

return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Task Title"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<textarea
placeholder="Task Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
></textarea>
<button type="submit">Add Task</button>
</form>
);
};

export default TaskForm;

TaskList.js

jsx

import React from 'react';

const TaskList = ({ tasks, onDelete }) => {
return (
<ul>
{tasks.map((task) => (
<li key={task._id}>
<h3>{task.title}</h3>
<p>{task.description}</p>
<button onClick={() => onDelete(task._id)}>Delete</button>
</li>
))}
</ul>
);
};

export default TaskList;

services/AuthService.js

javascript

const AuthService = {
getCurrentUser() {
// Implement logic to fetch current user from backend
return new Promise((resolve, reject) => {
// Mock user data
const user = {
username: 'john_doe',
email: 'john@example.com'
};
resolve(user);
});
}
};

export default AuthService;

services/TaskService.js

javascript

const TaskService = {
getTasks() {
// Implement logic to fetch tasks from backend
return new Promise((resolve, reject) => {
// Mock tasks data
const tasks = [
{ _id: 1, title: 'Task 1', description: 'Description 1' },
{ _id: 2, title: 'Task 2', description: 'Description 2' },
{ _id: 3, title: 'Task 3', description: 'Description 3' }
];
resolve(tasks);
});
},

createTask(taskData) {
// Implement logic to create task on backend
return new Promise((resolve, reject) => {
// Mock created task
const newTask = { ...taskData, _id: Date.now() };
resolve(newTask);
});
},

deleteTask(taskId) {
// Implement logic to delete task on backend
return new Promise((resolve, reject) => {
// Mock deletion
console.log(`Deleting task with ID: ${taskId}`);
resolve();
});
}
};

export default TaskService;

This is the frontend part of the application. It consists of React components for rendering tasks and task form, along with services for handling authentication and task operations.

For the backend part, you can use any backend technology of your choice (Node.js, Python Flask, etc.) along with a database (MongoDB, MySQL, etc.). Here’s a basic example using Node.js and Express:

Backend (Node.js + Express)

server.js

javascript

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 5000;

app.use(bodyParser.json());
app.use(cors());

let tasks = [
{ _id: 1, title: 'Task 1', description: 'Description 1' },
{ _id: 2, title: 'Task 2', description: 'Description 2' },
{ _id: 3, title: 'Task 3', description: 'Description 3' }
];

app.get('/tasks', (req, res) => {
res.json(tasks);
});

app.post('/tasks', (req, res) => {
const newTask = { ...req.body, _id: Date.now() };
tasks.push(newTask);
res.status(201).json(newTask);
});

app.delete('/tasks/:id', (req, res) => {
const taskId = parseInt(req.params.id);
tasks = tasks.filter(task => task._id !== taskId);
res.sendStatus(204);
});

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

This backend server exposes endpoints for fetching tasks, creating tasks, and deleting tasks.

To run the application:

  1. Create a new directory for your project.
  2. Inside the directory, create frontend and backend folders.
  3. Place the frontend files in the frontend folder and the backend files in the backend folder.
  4. Run npm install in both the frontend and backend folders to install dependencies.
  5. Run npm start in both folders to start the frontend and backend servers.
  6. Open your browser and navigate to http://localhost:3000 to view the application.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *