Andrew DeWitt
Andrew DeWitt

Reputation: 57

Need to have the user be able to edit profile with an edit button

I am working on a project and creating a website. the feature i am working on right now is the profile page for the user. i need to be able to have an edit button in the page that will allow the user to edit their name, username, email, and update password. The following is the code i have but i am unsure how to make everything work.

import React, {useEffect, useState} from "react";
import {useHistory} from "react-router-dom";
import axios from "axios";

const ProfilePage = () => {
    const [user, setUser] = useState({});
    const [sessionUrl,] = useState("/api/sessions/me");
    const history = useHistory();

    useEffect(() => {
         (async () => {
            try {
                const response = await axios.get(sessionUrl);
                setUser(response.data);
            } catch (err) {
                history.push({
                    pathname: "/account/login"
                });
            }
        })();
     }, []);

     return (
         <div>
             <div>Name: {user.displayName}</div>
             <div>Username: {user.username}</div>
             <div>Email: {user.email}</div>
         </div>
    );
 }

export default ProfilePage;

Upvotes: 2

Views: 8182

Answers (1)

Christian LSANGOLA
Christian LSANGOLA

Reputation: 3307

If you want to edit informations, what you should do is to provide a edit form with the users prefilled fields.Here is something very simple that i've created for you in Codesandbox.

Input.js for input field component

import React from "react";

export default ({ placeholder, type, value, handleInput, name }) => {
  return (
    <input
      type={type}
      name={name}
      value={value}
      onChange={handleInput}
      placeholder={placeholder}
    />
  );
};

For the EditForm component i've worked with some fake data from http://jsonplaceholder.typicode.com/ website to have some data to populate form.

In useEffect hook fetch some data from http://jsonplaceholder.typicode.com/users/1 to fetch a single ressource to populate the following form

import React, { useState, useEffect } from "react";
import Input from "./Input";
import axios from "axios";
import "./styles.css";

const INITIAL_STATE = {
  id: 0,
  name: "",
  email: ""
};
export default function App() {
  const [user, setUser] = useState(INITIAL_STATE);
  useEffect(() => {
    (async () => {
      try {
        const user = await axios.get(
          "https://jsonplaceholder.typicode.com/users/1"
        );
        setUser(user.data);
      } catch (error) {
        console.log(error);
      }
    })();
  }, []);

  const handleInput = (e) => {
    console.log(e.target.name, " : ", e.target.value);
    setUser({ ...user, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      console.log("Data for update : ", user);
      const response = await axios.put(`https://yourendpoint/${user.id}`, user);
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <div className="App">
      <h1>{user.name}</h1>
      <form onSubmit={handleSubmit}>
        <Input
          name="name"
          type="text"
          value={user.name}
          placeholder={"Your names"}
          handleInput={handleInput}
        />
        <br />
        <Input
          name="email"
          type="email"
          value={user.email}
          placeholder={"Your email"}
          handleInput={handleInput}
        />
        <br />
        <input type="submit" value="Update" />
      </form>
    </div>
  );
}

The input fields change onChange listener is handled by a method in the parent component component EditForm to update state with new data.Once the user click the update button there is a handleSubmit methode that is called by the onSubmit event listener from the form JSX tag.For data i've not created a complete form with all the data coming form the jsonplaceholder server for example purposes.

For the submit action,you only have to call the put method with whatever ajax library that you're using.

Here s the sandbox link : https://codesandbox.io/s/blissful-dirac-rboiy

I hope it helped

Upvotes: 2

Related Questions