Spaces:
Sleeping
Sleeping
import BasicTemplate from "../templates/BasicTemplate"; | |
import { Container, Form, Row, Col, Card, Alert, Button, Image } from "react-bootstrap"; | |
import React, { useState, useEffect } from "react"; | |
import validator from "validator"; | |
import axios from "axios"; | |
import DataStorage from "../organisms/DataStorage"; | |
export default function UserInfoPage() { | |
// fetch data: | |
const [error, setErrors] = useState(""); | |
const [initialData, setInitialData] = useState(null); | |
const [formData, setFormData] = useState({ | |
avatar: "/default_avatar.jpg", | |
full_name: "", | |
phone_number: "", | |
address: "", | |
email: "", | |
password: "", | |
confirmPassword: "", | |
}); | |
useEffect(() => { | |
axios | |
.get(process.env.REACT_APP_API_URL + '/authentication/profile', { | |
headers: { | |
Authorization: `Bearer ${DataStorage.get('accessToken')}`, | |
}, | |
}) | |
.then((response) => { | |
if (response.status === 401) { | |
// phiên hết hạn | |
setErrors(JSON.stringify(response)); | |
} else { | |
const { avatar, full_name, address, phone_number, email } = response.data; | |
const fetchedData = { | |
avatar: avatar || "/default_avatar.jpg", | |
full_name: full_name || "", | |
phone_number: phone_number || "", | |
address: address || "", | |
email: email || "", | |
password: "", | |
confirmPassword: "", | |
}; | |
if (fetchedData.full_name !== DataStorage.get('username')) DataStorage.set('username', fetchedData.full_name) | |
setInitialData(fetchedData); | |
setFormData(fetchedData); | |
} | |
}) | |
.catch((error) => { | |
setErrors(JSON.stringify(error)); | |
}); | |
}, []); | |
// console.log('formdata', formData); | |
// console.log('initialdata', initialData); | |
// State để hiển thị lỗi khi validation | |
const [isChanged, setChanged] = useState(false); | |
const handleChange = (e) => { | |
const { name, value } = e.target; | |
setFormData({ ...formData, [name]: value }); | |
}; | |
// Hàm xử lý thay đổi avatar | |
const handleAvatarChange = (e) => { | |
const file = e.target.files[0]; | |
if (file) { | |
const reader = new FileReader(); | |
reader.onloadend = () => { | |
setFormData((prevData) => ({ | |
...prevData, | |
avatar: reader.result // Cập nhật ảnh đại diện | |
})); | |
}; | |
reader.readAsDataURL(file); | |
setChanged(true); | |
} | |
}; | |
useEffect(() => { | |
const hasChanges = () => { | |
if (initialData) { | |
for (let key in formData) { | |
if (formData[key] !== initialData[key]) { | |
return true; | |
} | |
} | |
return false; | |
} else { | |
return false; | |
} | |
}; | |
setChanged(hasChanges()); | |
}, [formData, initialData]); | |
const handleSubmit = async (e) => { | |
e.preventDefault(); | |
setChanged(false); // prevent another click | |
if (formData.phone_number.trim() !== "" && !validator.isMobilePhone(formData.phone_number, 'vi-VN')) setErrors("Số điện thoại không hợp lệ"); | |
else if (formData.email.trim() !== "" && !validator.isEmail(formData.email)) setErrors("Email không hợp lệ"); | |
else if (formData.password !== "" && formData.confirmPassword !== formData.password) setErrors("Mật khẩu không khớp"); | |
else { | |
// let avatarBase64 = null; | |
// if (formData.avatar) { | |
// // Chuyển ảnh đại diện thành chuỗi Base64 | |
// avatarBase64 = await new Promise((resolve, reject) => { | |
// const reader = new FileReader(); | |
// reader.onloadend = () => resolve(reader.result.split(",")[1]); // Chỉ lấy phần Base64 | |
// reader.onerror = (error) => reject(error); | |
// reader.readAsDataURL(formData.avatar); | |
// }); | |
// } | |
let data = {}; | |
// if (avatarBase64) data.avatar = avatarBase64; | |
if (formData.full_name.trim() !== "" && formData.full_name.trim() !== initialData.full_name) data.full_name = formData.full_name.trim(); | |
if (formData.phone_number.trim() !== "" && formData.phone_number.trim() !== initialData.phone_number) data.phone_number = formData.phone_number.trim(); | |
if (formData.address.trim() !== "" && formData.address.trim() !== initialData.address) data.address = formData.address.trim(); | |
if (formData.email.trim() !== "" && formData.email.trim() !== initialData.email) data.email = formData.email.trim(); | |
if (formData.password.trim() !== "") data.hash_password = formData.password; | |
// gửi request ở đây | |
axios.post(process.env.REACT_APP_API_URL + '/users/updateUser', data, { | |
headers: { | |
Authorization: `Bearer ${DataStorage.get('accessToken')}`, | |
} | |
}).then((response) => { | |
if (response.status === 200 || response.status === 201) { | |
window.location.reload(); // cập nhật lại thông tin | |
} else { | |
setErrors(JSON.stringify(response)); | |
} | |
}).catch((error) => setErrors(JSON.stringify(error))); | |
} | |
}; | |
return <BasicTemplate content={ | |
( | |
<Container fluid className="d-flex align-items-center justify-content-center mt-5"> | |
<Row> | |
<Col xs={1} md={2}></Col> | |
<Col xs={10} md={8}> | |
<Card style={{ width: '30rem' }} className='justify-content-center'> | |
<Card.Header> | |
<Card.Title className='mt-1 text-center'>Thông tin khách hàng</Card.Title> | |
</Card.Header> | |
<Card.Body> | |
<Form onSubmit={handleSubmit}> | |
{error && <Alert variant="danger">{error}</Alert>} | |
<Row className="mb-3"> | |
<Col xs={12} md={6} className="text-center"> | |
{/*Image*/} | |
<Image | |
src={formData.avatar} // Hiển thị ảnh đại diện từ formData | |
alt="User Avatar" | |
roundedCircle | |
width={120} | |
height={120} | |
/> | |
<Form.Group controlId="formAvatar"> | |
<Form.Label>Ảnh đại diện</Form.Label> | |
<Form.Control type="file" accept="image/*" onChange={handleAvatarChange} /> | |
</Form.Group> | |
</Col> | |
<Col xs={12} md={6}> | |
<Form.Group controlId="formUsername"> | |
<Form.Label>Họ tên người dùng</Form.Label> | |
<Form.Control | |
type="text" | |
name="full_name" | |
placeholder="Họ tên người dùng" | |
value={formData.full_name} | |
onChange={handleChange} | |
/> | |
</Form.Group> | |
</Col> | |
</Row> | |
<Form.Group controlId="formPhone" className="mb-3"> | |
<Form.Label>Số điện thoại</Form.Label> | |
<Form.Control | |
type="text" | |
name="phone_number" | |
placeholder="Số điện thoại" | |
value={formData.phone_number} | |
onChange={handleChange} | |
/> | |
</Form.Group> | |
<Form.Group controlId="formAddress" className="mb-3"> | |
<Form.Label>Địa chỉ giao hàng mặc định</Form.Label> | |
<Form.Control | |
type="text" | |
name="address" | |
placeholder="Địa chỉ giao hàng" | |
value={formData.address} | |
onChange={handleChange} | |
/> | |
</Form.Group> | |
<Form.Group controlId="formEmail" className="mb-3"> | |
<Form.Label>Email</Form.Label> | |
<Form.Control | |
type="text" | |
name="email" | |
placeholder="Email" | |
value={formData.email} | |
onChange={handleChange} | |
/> | |
</Form.Group> | |
<Form.Group controlId="formPassword" className="mb-3"> | |
<Form.Label>Password</Form.Label> | |
<Form.Control | |
type="password" | |
name="password" | |
placeholder="********" | |
value={formData.password} | |
onChange={handleChange} | |
/> | |
</Form.Group> | |
<Form.Group controlId="formConfirmPassword" className="mb-3"> | |
<Form.Label>Nhập lại Password</Form.Label> | |
<Form.Control | |
type="password" | |
name="confirmPassword" | |
placeholder="********" | |
value={formData.confirmPassword} | |
onChange={handleChange} | |
/> | |
</Form.Group> | |
<Button variant="primary" type="submit" disabled={!isChanged}> | |
Cập nhật | |
</Button> | |
</Form> | |
</Card.Body> | |
</Card> | |
</Col> | |
<Col xs={1} md={2}></Col> | |
</Row> | |
</Container> | |
) | |
} /> | |
} |