Anurag Sharma
Anurag Sharma

Reputation: 321

How to change Input fields values in React?

I am not being able to change input fields.Any suggestion?

const MiddlePanel = ({ user }) => {

  const history = useHistory();

  const [data, setData] = useState({

    firstname: '',
    lastname: '',
    email: '',
    phoneNo: '',
  });

  const { firstname, lastname, email, phoneNo } = data;

  useEffect(() => {
    
    const fetchUser = async () => {

      const res = await axios.get(`http://localhost:5000/users/${user._id}`);
      setData({
        firstname: res.data.firstname,
        lastname: res.data.lastname,
        email: res.data.email,
        password: res.data.password,
      });
    };
    fetchUser();
  }, [user._id]);

  const handleChange = (e) => {

    setData({ ...data, [e.target.name]: e.target.value });

  };

  const handleSubmit = async (e) => {

    e.preventDefault();

    const newUser = { firstname, lastname, email, phoneNo };
    try {
      const config = {
        headers: {
          "Content-Type": "application/json",
        },
      };
      const body = JSON.stringify(newUser);
      await axios.patch(
        `http://localhost:5000/users/${user._id}`,
        body,
        config
      );
      history.push("/");
    } catch (err) {}
  };
 
 return (

    <div>
      <Form onSubmit={handleSubmit}>
        <Input
          type="text"
          name="firstname"
          onChange={handleChange}
          value={user.firstname}
        />
        <Input
          type="text"
          name="lastname"
          onChange={handleChange}
          value={user.lastname}
        />
        <Input
          type="email"
          name="email"
          onChange={handleChange}
          value={user.email}
        />
        <Input
          type="tel"
          name="phoneNo"
          onChange={handleChange}
          value={user.phoneNo}
        />
        <PrimaryButton className="btn btn-primary" style={{ width: "100%" }}>
          Update
        </PrimaryButton>
      </Form>
    </div>
  );
};

Upvotes: 0

Views: 47

Answers (1)

Francisco
Francisco

Reputation: 1773

I think you should use data.firstname instead of user for the value property

    <div>
      <Form onSubmit={handleSubmit}>
        <Input
          type="text"
          name="firstname"
          onChange={handleChange}
          value={data.firstname}
        />
        <Input
          type="text"
          name="lastname"
          onChange={handleChange}
          value={data.lastname}
        />
        <Input
          type="email"
          name="email"
          onChange={handleChange}
          value={data.email}
        />
        <Input
          type="tel"
          name="phoneNo"
          onChange={handleChange}
          value={data.phoneNo}
        />
        <PrimaryButton className="btn btn-primary" style={{ width: "100%" }}>
          Update
        </PrimaryButton>
      </Form>
    </div>

Upvotes: 1

Related Questions