React Form Submission Logs Updated Data but Does Not Update Database or Navigate to Tasks Page

now i ‘m creating endpoint for editing task for to do app using laravel and react.js
the end point i tested it using postman and it returns success response http://localhost:8000/api/tasks/4
and the body is

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> {
"user_id": 1,
"title": "Updated Task4",
"description": "Updated description",
"status": "completed",
"due_date": "2024-08-01",
"category_id": 1
}
</code>
<code> { "user_id": 1, "title": "Updated Task4", "description": "Updated description", "status": "completed", "due_date": "2024-08-01", "category_id": 1 } </code>
 {
    "user_id": 1,
    "title": "Updated Task4",
    "description": "Updated description",
    "status": "completed",
    "due_date": "2024-08-01",
    "category_id": 1
}

and here’s the response

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
"data": {
"id": 4,
"user_id": 1,
"title": "Updated Task4",
"description": "Updated description",
"status": "completed",
"due_date": "2024-08-01",
"category_id": 1,
"created_at": "2024-07-23T21:12:40.000000Z",
"updated_at": "2024-07-25T00:00:22.000000Z"
}
}
</code>
<code>{ "data": { "id": 4, "user_id": 1, "title": "Updated Task4", "description": "Updated description", "status": "completed", "due_date": "2024-08-01", "category_id": 1, "created_at": "2024-07-23T21:12:40.000000Z", "updated_at": "2024-07-25T00:00:22.000000Z" } } </code>
{
    "data": {
        "id": 4,
        "user_id": 1,
        "title": "Updated Task4",
        "description": "Updated description",
        "status": "completed",
        "due_date": "2024-08-01",
        "category_id": 1,
        "created_at": "2024-07-23T21:12:40.000000Z",
        "updated_at": "2024-07-25T00:00:22.000000Z"
    }
}
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> by creating edit-task component in react and implement this code in it
</code>
<code> by creating edit-task component in react and implement this code in it </code>
 by creating edit-task component in react and implement this code in it 
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import axios from 'axios';
import { Helmet } from 'react-helmet';
import Joi from 'joi';
export default function EditTask() {
const { id } = useParams();
const navigate = useNavigate();
const [task, setTask] = useState({
user_id: '', // Initially empty
title: '',
description: '',
status: 'pending',
due_date: '',
category_id: ''
});
const [categories, setCategories] = useState([]);
const [loading, setLoading] = useState(false);
const [errors, setErrors] = useState({});
useEffect(() => {
fetchCategories();
fetchTask();
}, []);
const fetchCategories = async () => {
try {
const response = await axios.get('http://localhost:8000/api/categories');
setCategories(response.data.data);
} catch (error) {
console.error('Error fetching categories:', error);
}
};
const fetchTask = async () => {
try {
const response = await axios.get(`http://localhost:8000/api/tasks/${id}`);
setTask(response.data.data);
} catch (error) {
console.error('Error fetching task:', error);
}
};
const schema = Joi.object({
user_id: Joi.number().required(),
title: Joi.string().min(3).max(255).required(),
description: Joi.string().min(5).max(255).allow(''),
status: Joi.string().valid('pending', 'completed').required(),
due_date: Joi.date().allow(''),
category_id: Joi.number().required()
});
const handleChange = (e) => {
const { name, value } = e.target;
setTask(prevTask => ({
...prevTask,
[name]: value
}));
};
const handleSubmit = async (e) => {
e.preventDefault();
console.log('Form submitted'); // Debug log
console.log('Task data before submission:', task); // Log task data
const { error } = schema.validate(task, { abortEarly: false });
if (error) {
const validationErrors = {};
error.details.forEach(detail => {
validationErrors[detail.path[0]] = detail.message;
});
setErrors(validationErrors);
return;
}
setErrors({});
setLoading(true);
try {
const response = await axios.put(`http://localhost:8000/api/tasks/${id}`, task, {
headers: {
'Content-Type': 'application/json',
},
});
console.log('Response from server:', response); // Debug log
console.log('Updated task data:', response.data); // Debug log
if (response.status === 200) {
navigate('/tasks');
} else {
setErrors({ form: 'Failed to update task. Please try again.' });
}
} catch (error) {
console.error('Error updating task:', error);
setErrors({ form: 'Failed to update task. Please check the form data.' });
} finally {
setLoading(false);
}
};
return (
<>
<Helmet>
<meta charSet="utf-8" />
<title>Edit Task</title>
</Helmet>
<div className="container mt-5">
<h1>Edit Task</h1>
<form onSubmit={handleSubmit}>
<div className="mb-3">
<label htmlFor="title" className="form-label">Title</label>
<input
type="text"
className="form-control"
id="title"
name="title"
value={task.title}
onChange={handleChange}
placeholder="Enter task title"
required
/>
{errors.title && <small className="text-danger">{errors.title}</small>}
</div>
<div className="mb-3">
<label htmlFor="description" className="form-label">Description</label>
<textarea
className="form-control"
id="description"
name="description"
value={task.description}
onChange={handleChange}
placeholder="Enter task description"
/>
{errors.description && <small className="text-danger">{errors.description}</small>}
</div>
<div className="mb-3">
<label htmlFor="status" className="form-label">Status</label>
<select
className="form-select"
id="status"
name="status"
value={task.status}
onChange={handleChange}
required
>
<option value="pending">Pending</option>
<option value="completed">Completed</option>
</select>
{errors.status && <small className="text-danger">{errors.status}</small>}
</div>
<div className="mb-3">
<label htmlFor="due_date" className="form-label">Due Date</label>
<input
type="date"
className="form-control"
id="due_date"
name="due_date"
value={task.due_date}
onChange={handleChange}
/>
{errors.due_date && <small className="text-danger">{errors.due_date}</small>}
</div>
<div className="mb-3">
<label htmlFor="category_id" className="form-label">Category</label>
<select
className="form-select"
id="category_id"
name="category_id"
value={task.category_id}
onChange={handleChange}
required
>
<option value="">Select a category</option>
{categories.map(cat => (
<option key={cat.id} value={cat.id}>{cat.name}</option>
))}
</select>
{errors.category_id && <small className="text-danger">{errors.category_id}</small>}
</div>
{errors.form && <div className="alert alert-danger">{errors.form}</div>}
<button type="submit" className="btn invadebtn" disabled={loading}>
{loading ? <span className="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> : 'Update Task'}
</button>
</form>
</div>
</>
);
}
</code>
<code>import React, { useState, useEffect } from 'react'; import { useParams, useNavigate } from 'react-router-dom'; import axios from 'axios'; import { Helmet } from 'react-helmet'; import Joi from 'joi'; export default function EditTask() { const { id } = useParams(); const navigate = useNavigate(); const [task, setTask] = useState({ user_id: '', // Initially empty title: '', description: '', status: 'pending', due_date: '', category_id: '' }); const [categories, setCategories] = useState([]); const [loading, setLoading] = useState(false); const [errors, setErrors] = useState({}); useEffect(() => { fetchCategories(); fetchTask(); }, []); const fetchCategories = async () => { try { const response = await axios.get('http://localhost:8000/api/categories'); setCategories(response.data.data); } catch (error) { console.error('Error fetching categories:', error); } }; const fetchTask = async () => { try { const response = await axios.get(`http://localhost:8000/api/tasks/${id}`); setTask(response.data.data); } catch (error) { console.error('Error fetching task:', error); } }; const schema = Joi.object({ user_id: Joi.number().required(), title: Joi.string().min(3).max(255).required(), description: Joi.string().min(5).max(255).allow(''), status: Joi.string().valid('pending', 'completed').required(), due_date: Joi.date().allow(''), category_id: Joi.number().required() }); const handleChange = (e) => { const { name, value } = e.target; setTask(prevTask => ({ ...prevTask, [name]: value })); }; const handleSubmit = async (e) => { e.preventDefault(); console.log('Form submitted'); // Debug log console.log('Task data before submission:', task); // Log task data const { error } = schema.validate(task, { abortEarly: false }); if (error) { const validationErrors = {}; error.details.forEach(detail => { validationErrors[detail.path[0]] = detail.message; }); setErrors(validationErrors); return; } setErrors({}); setLoading(true); try { const response = await axios.put(`http://localhost:8000/api/tasks/${id}`, task, { headers: { 'Content-Type': 'application/json', }, }); console.log('Response from server:', response); // Debug log console.log('Updated task data:', response.data); // Debug log if (response.status === 200) { navigate('/tasks'); } else { setErrors({ form: 'Failed to update task. Please try again.' }); } } catch (error) { console.error('Error updating task:', error); setErrors({ form: 'Failed to update task. Please check the form data.' }); } finally { setLoading(false); } }; return ( <> <Helmet> <meta charSet="utf-8" /> <title>Edit Task</title> </Helmet> <div className="container mt-5"> <h1>Edit Task</h1> <form onSubmit={handleSubmit}> <div className="mb-3"> <label htmlFor="title" className="form-label">Title</label> <input type="text" className="form-control" id="title" name="title" value={task.title} onChange={handleChange} placeholder="Enter task title" required /> {errors.title && <small className="text-danger">{errors.title}</small>} </div> <div className="mb-3"> <label htmlFor="description" className="form-label">Description</label> <textarea className="form-control" id="description" name="description" value={task.description} onChange={handleChange} placeholder="Enter task description" /> {errors.description && <small className="text-danger">{errors.description}</small>} </div> <div className="mb-3"> <label htmlFor="status" className="form-label">Status</label> <select className="form-select" id="status" name="status" value={task.status} onChange={handleChange} required > <option value="pending">Pending</option> <option value="completed">Completed</option> </select> {errors.status && <small className="text-danger">{errors.status}</small>} </div> <div className="mb-3"> <label htmlFor="due_date" className="form-label">Due Date</label> <input type="date" className="form-control" id="due_date" name="due_date" value={task.due_date} onChange={handleChange} /> {errors.due_date && <small className="text-danger">{errors.due_date}</small>} </div> <div className="mb-3"> <label htmlFor="category_id" className="form-label">Category</label> <select className="form-select" id="category_id" name="category_id" value={task.category_id} onChange={handleChange} required > <option value="">Select a category</option> {categories.map(cat => ( <option key={cat.id} value={cat.id}>{cat.name}</option> ))} </select> {errors.category_id && <small className="text-danger">{errors.category_id}</small>} </div> {errors.form && <div className="alert alert-danger">{errors.form}</div>} <button type="submit" className="btn invadebtn" disabled={loading}> {loading ? <span className="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> : 'Update Task'} </button> </form> </div> </> ); } </code>
import React, { useState, useEffect } from 'react'; 
import { useParams, useNavigate } from 'react-router-dom';
import axios from 'axios';
import { Helmet } from 'react-helmet';
import Joi from 'joi';

export default function EditTask() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [task, setTask] = useState({
    user_id: '', // Initially empty
    title: '',
    description: '',
    status: 'pending',
    due_date: '',
    category_id: ''
  });
  const [categories, setCategories] = useState([]);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState({});

  useEffect(() => {
    fetchCategories();
    fetchTask();
  }, []);

  const fetchCategories = async () => {
    try {
      const response = await axios.get('http://localhost:8000/api/categories');
      setCategories(response.data.data);
    } catch (error) {
      console.error('Error fetching categories:', error);
    }
  };

  const fetchTask = async () => {
    try {
      const response = await axios.get(`http://localhost:8000/api/tasks/${id}`);
      setTask(response.data.data);
    } catch (error) {
      console.error('Error fetching task:', error);
    }
  };

  const schema = Joi.object({
    user_id: Joi.number().required(),
    title: Joi.string().min(3).max(255).required(),
    description: Joi.string().min(5).max(255).allow(''),
    status: Joi.string().valid('pending', 'completed').required(),
    due_date: Joi.date().allow(''),
    category_id: Joi.number().required()
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setTask(prevTask => ({
      ...prevTask,
      [name]: value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log('Form submitted'); // Debug log
    console.log('Task data before submission:', task); // Log task data

    const { error } = schema.validate(task, { abortEarly: false });
    if (error) {
      const validationErrors = {};
      error.details.forEach(detail => {
        validationErrors[detail.path[0]] = detail.message;
      });
      setErrors(validationErrors);
      return;
    }

    setErrors({});
    setLoading(true);

    try {
      const response = await axios.put(`http://localhost:8000/api/tasks/${id}`, task, {
        headers: {
          'Content-Type': 'application/json',
        },
      });

      console.log('Response from server:', response); // Debug log
      console.log('Updated task data:', response.data); // Debug log

      if (response.status === 200) {
        navigate('/tasks');
      } else {
        setErrors({ form: 'Failed to update task. Please try again.' });
      }
    } catch (error) {
      console.error('Error updating task:', error);
      setErrors({ form: 'Failed to update task. Please check the form data.' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <Helmet>
        <meta charSet="utf-8" />
        <title>Edit Task</title>
      </Helmet>
      <div className="container mt-5">
        <h1>Edit Task</h1>
        <form onSubmit={handleSubmit}>
          <div className="mb-3">
            <label htmlFor="title" className="form-label">Title</label>
            <input
              type="text"
              className="form-control"
              id="title"
              name="title"
              value={task.title}
              onChange={handleChange}
              placeholder="Enter task title"
              required
            />
            {errors.title && <small className="text-danger">{errors.title}</small>}
          </div>
          <div className="mb-3">
            <label htmlFor="description" className="form-label">Description</label>
            <textarea
              className="form-control"
              id="description"
              name="description"
              value={task.description}
              onChange={handleChange}
              placeholder="Enter task description"
            />
            {errors.description && <small className="text-danger">{errors.description}</small>}
          </div>
          <div className="mb-3">
            <label htmlFor="status" className="form-label">Status</label>
            <select
              className="form-select"
              id="status"
              name="status"
              value={task.status}
              onChange={handleChange}
              required
            >
              <option value="pending">Pending</option>
              <option value="completed">Completed</option>
            </select>
            {errors.status && <small className="text-danger">{errors.status}</small>}
          </div>
          <div className="mb-3">
            <label htmlFor="due_date" className="form-label">Due Date</label>
            <input
              type="date"
              className="form-control"
              id="due_date"
              name="due_date"
              value={task.due_date}
              onChange={handleChange}
            />
            {errors.due_date && <small className="text-danger">{errors.due_date}</small>}
          </div>
          <div className="mb-3">
            <label htmlFor="category_id" className="form-label">Category</label>
            <select
              className="form-select"
              id="category_id"
              name="category_id"
              value={task.category_id}
              onChange={handleChange}
              required
            >
              <option value="">Select a category</option>
              {categories.map(cat => (
                <option key={cat.id} value={cat.id}>{cat.name}</option>
              ))}
            </select>
            {errors.category_id && <small className="text-danger">{errors.category_id}</small>}
          </div>
          {errors.form && <div className="alert alert-danger">{errors.form}</div>}
          <button type="submit" className="btn invadebtn" disabled={loading}>
            {loading ? <span className="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> : 'Update Task'}
          </button>
        </form>
      </div>
    </>
  );
}

it doesn’t work it logs in the console the updated data but neither it updated in the database or navigate me to tasks page

to update the database && and navigate me to tasks page

New contributor

Gamal Sobhy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật