I’m trying to create a task app. when saving it, the server says successful
[{"taskName":"Join Group","completed":true},{"taskName":"Follow Channel","completed":true},{"taskName":"Follow Twitter","completed":false},{"taskName":"Visit Website","completed":false},{"taskName":"Visit Launchpad","completed":false}]
However, it is not saved in the database, see the follow channel task
[{"taskName": "Join Group", "completed": true}, {"taskName": "Follow Channel", "completed": false}, {"taskName": "Follow Twitter", "completed": false}, {"taskName": "Visit Website", "completed": false}, {"taskName": "Visit Launchpad", "completed": false}]
Here the UI
const handleTaskClick = (e: React.MouseEvent<HTMLAnchorElement>, taskName: string, link: string, isTaskCompleted: boolean) => {
e.preventDefault();
if (!isTaskCompleted && username) {
sessionStorage.setItem('currentPage', JSON.stringify({ taskName }));
axios.post('/api/completeTask', { username, taskName })
.then(response => {
console.log('Updated Task Data:', response.data);
setTaskData(response.data);
window.open(link, '_blank');
})
.catch(error => {
console.error('Error completing task', error.response?.data || error.message);
});
}
};
and here the backend
// models/Task.js
const { sequelize, DataTypes } = require("../config/mysql-sequelize");
module.exports = (sequelize, DataTypes) => {
const Task = sequelize.define('Task', {
username: { type: DataTypes.STRING, allowNull: false },
tasks: {
type: DataTypes.JSON,
defaultValue: []
},
claimedAmount: { type: DataTypes.FLOAT, defaultValue: 0 }
}, {
timestamps: true
});
return Task;
};
// routes/task.js
const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const { Task } = require('../models');
const getTasksConfig = () => {
const filePath = path.join(__dirname, '../config/tasks.json');
if (fs.existsSync(filePath)) {
const fileContent = fs.readFileSync(filePath, 'utf8');
try {
return JSON.parse(fileContent);
} catch (error) {
console.error('Error parsing JSON:', error);
return [];
}
} else {
console.error('File not found:', filePath);
return [];
}
};
router.get('/tasksConfig', (req, res) => {
try {
const tasksConfig = getTasksConfig();
res.json(tasksConfig);
} catch (error) {
res.status(500).json({ message: 'Error loading tasks configuration' });
}
});
// Endpoint untuk mendapatkan data tugas pengguna
router.get('/taskData', async (req, res) => {
const { username } = req.query;
try {
const taskData = await Task.findOne({ where: { username } });
if (taskData) {
res.json(taskData);
} else {
res.status(404).json({ message: 'Task data not found' });
}
} catch (error) {
res.status(500).json({ message: 'Server error' });
}
});
router.post('/completeTask', async (req, res) => {
const { username, taskName } = req.body;
console.log(`Received request to complete task: ${taskName} for user: ${username}`);
try {
const tasksConfig = getTasksConfig();
const taskConfig = tasksConfig.find(t => t.taskName === taskName);
if (!taskConfig) {
console.log(`Task configuration not found for taskName: ${taskName}`);
return res.status(400).json({ message: 'Invalid task name' });
}
let taskData = await Task.findOne({ where: { username } });
if (!taskData) {
console.log(`No task data found for username: ${username}. Creating new task data.`);
taskData = new Task({
username,
tasks: tasksConfig.map(t => ({ taskName: t.taskName, completed: false })),
claimedAmount: 0,
});
} else {
console.log(`Existing task data found for username: ${username}`);
const existingTaskNames = taskData.tasks.map(t => t.taskName);
const newTasks = tasksConfig.filter(t => !existingTaskNames.includes(t.taskName));
if (newTasks.length > 0) {
console.log(`Adding new tasks: ${JSON.stringify(newTasks)}`);
taskData.tasks.push(...newTasks.map(t => ({ taskName: t.taskName, completed: false })));
}
}
const task = taskData.tasks.find(t => t.taskName === taskName);
if (task) {
if (!task.completed) {
console.log(`Completing task: ${taskName} for user: ${username}`);
task.completed = true;
taskData.claimedAmount += taskConfig.reward;
await taskData.save();
console.log(`Task completed. Updated task data: ${JSON.stringify(taskData)}`);
res.json(taskData);
} else {
console.log(`Task: ${taskName} already completed for user: ${username}`);
res.status(400).json({ message: 'Task already completed' });
}
} else {
console.log(`Task: ${taskName} not found in task data for user: ${username}`);
res.status(400).json({ message: 'Task not found' });
}
} catch (error) {
console.error('Error completing task:', error);
res.status(500).json({ message: 'Server error' });
}
});
router.get('/getTaskAmount', async (req, res) => {
const { username } = req.query;
try {
const taskData = await Task.findOne({ where: { username } });
if (taskData) {
res.json({ claimedAmount: taskData.claimedAmount });
} else {
res.status(404).json({ message: 'User not found' });
}
} catch (error) {
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;
What causes data not to be saved correctly to the database?