We first create our EditProfile component
src/user/EditProfile.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import React, { Component } from 'react'; import { IsAuthenticated } from '../auth'; import { Redirect } from 'react-router-dom'; import { getUserInfo, UpdateUser } from './apiUser'; class EditProfile extends Component { constructor() { super() this.state = {} } render() { return ( <div className="container"> <h2 className="mt-5 mb-5">Edit Profile</h2> </div> ) } } export default EditProfile |
Then, we add a Route to our EditProfile component. Whenever this link is clicked, it hits our EditProfile component.
src/MainRouter.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
... ... import EditProfile from './user/EditProfile' const MainRouter = () => ( <div> <Menu /> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/users" component={Users} /> <Route exact path="/signup" component={Signup} /> <Route exact path="/signin" component={Signin} /> <Route exact path="/user/:userId" component={Profile} /> <Route exact path="/user/edit/:userId" component={EditProfile} /> </Switch> </div> ) export default MainRouter; |
Make sure we implement UpdateUser fetch operation, which does a PUT operation on the server for a particular user. That way, we can tell the server to update this particular user with this particular data.
Remember that when we give the user data in body, we need to stringify it. The server does not take objects as data. It takes a string.
If you were to send a body, the updateUser function on the server side won’t be triggered and it will be hard to debug. So make sure you always JSON stringify body data.
src/user/apiUser.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
export const UpdateUser = async (userId, token, user) => { return await fetch(`http://localhost:8080/user/${userId}`, { method: "PUT", mode: "cors", headers: { Accept : "application/json", "Content-Type": "application/json", Authorization: `Bearer ${token}`, 'Access-Control-Allow-Origin':'*' }, body: JSON.stringify(user) // remember to json stringify this or else, server side can't receive such data }) .then(response => { return response.json() }) .catch(err => { return err }) } |
EditProfile component source
Editing forms is about presenting a html form with textfield controls. We then put our state’s value in the textfield’s value property. Our state has already been updated with the latest value from the server via the initUserID function when the component was loaded.
1 2 3 4 5 6 7 8 9 10 11 12 |
renderEditForm = (name, email, password) => { return (<form> <div className="form-group"> <label className="text-muted">Name</label> <input onChange={this.handleChange("name")} type="text" className="form-control" value={name || ""} /> </div> ... ... |
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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
import React, { Component } from 'react'; import { IsAuthenticated } from '../auth'; import { Redirect } from 'react-router-dom'; import { getUserInfo, UpdateUser } from './apiUser'; // 1) get user information from backend based on user id class EditProfile extends Component { constructor() { super() this.state = { redirectToProfile: false, password: "", email: "", name: "", id: "", error: "", } } handleChange = (name) => (event) => { this.setState({ [name] : event.target.value }) } // in our Node API // auth.js - router.post('/signup', userSignupValidator, signup) clickUpdate = event => { event.preventDefault() if (this.isValid()) { const { name, email, password } = this.state const user = { name, email, password: password || undefined } const userId = this.props.match.params.userId; const token = IsAuthenticated().token; UpdateUser(userId, token, user).then(data => { console.log('clickUpdate', data) if (data.error) { this.setState({ error: data.error }) } else { this.setState({ redirectToProfile: true }) } }) } } renderEditForm = (name, email, password) => { return (<form> <div className="form-group"> <label className="text-muted">Name</label> <input onChange={this.handleChange("name")} type="text" className="form-control" value={name || ""} /> </div> <div className="form-group"> <label className="text-muted">Email</label> <input onChange={this.handleChange("email")} type="email" className="form-control" value={email || ""} /> </div> <div className="form-group"> <label className="text-muted">Password</label> <input onChange={this.handleChange("password")} type="password " className="form-control" value={password || ""} /> </div> <button onClick={this.clickUpdate} className="btn btn-raised btn-primary">Update</button> </form>); } initUserID = userId => { let token = IsAuthenticated().token getUserInfo(userId, token) .then(data => { if (data.error) { this.setState({ redirectToSignin: true }) } else { this.setState({ id: data._id, name: data.name, email: data.email }) } }) } componentDidMount() { console.log('user/EditProfile.js', 'componentDidMount'); const userId = this.props.match.params.userId this.initUserID(userId) } isValid = () => { const { name, email, password } = this.state if (name.length == 0) { this.setState({ error: "name is required"}) return false } if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) { this.setState({ error: "Email is required"}) return false } if (password.length >= 1 && password.length <= 5) { this.setState({ error: "Password must be at least 6 characters"}) return false } return true; } render() { const { id, name, email, password, redirectToProfile, error } = this.state if (redirectToProfile) { return <Redirect to={`/user/${id}`} /> } return ( <div className="container"> <h2 className="mt-5 mb-5">Edit Profile</h2> <div className="alert alert-danger" style={{ display: error ? "" : "none" }} > {error} </div> {this.renderEditForm(name, email, password)} </div> ) } } export default EditProfile |