File size: 3,168 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
import React, { useState, useEffect } from 'react';
import Layout from '../core/Layout';
import { isAuthenticated } from '../auth';
/* eslint-disable no-unused-vars */
import { Link, Redirect } from 'react-router-dom';
import { read, update, updateUser } from './apiUser';
const Profile = ({ match }) => {
const [values, setValues] = useState({
name: '',
email: '',
password: '',
error: false,
success: false
});
const { token } = isAuthenticated();
const { name, email, password, error, success } = values;
const init = userId => {
// console.log(userId);
read(userId, token).then(data => {
if (data.error) {
setValues({ ...values, error: true });
} else {
setValues({ ...values, name: data.name, email: data.email });
}
});
};
useEffect(() => {
init(match.params.userId);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleChange = name => e => {
setValues({ ...values, error: false, [name]: e.target.value });
};
const clickSubmit = e => {
e.preventDefault();
update(match.params.userId, token, { name, email, password }).then(data => {
if (data.error) {
// console.log(data.error);
alert(data.error);
} else {
updateUser(data, () => {
setValues({
...values,
name: data.name,
email: data.email,
success: true
});
});
}
});
};
const redirectUser = success => {
if (success) {
return <Redirect to="/cart" />;
}
};
const profileUpdate = (name, email, password) => (
<form>
<div className="form-group">
<label className="text-muted">Name</label>
<input type="text" onChange={handleChange('name')} className="form-control" value={name} />
</div>
<div className="form-group">
<label className="text-muted">Email</label>
<input type="email" onChange={handleChange('email')} className="form-control" value={email} />
</div>
<div className="form-group">
<label className="text-muted">Password</label>
<input type="password" onChange={handleChange('password')} className="form-control" value={password} />
</div>
<button onClick={clickSubmit} className="btn btn-primary">
Submit
</button>
</form>
);
return (
<Layout title="Profile" description="Update your profile" className="container mt-5 border rounded p-3 shadow-lg bg-light">
<h2 className="mb-4 p-2 bg-success text-white text-center font-weight-bold rounded shadow">Profile update</h2>
{profileUpdate(name, email, password)}
{redirectUser(success)}
</Layout>
);
};
export default Profile;
|