Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

javascript - How can I send data from this reactjs form to a database?

I want to link this small react project to a database, it's my first time so I don't really know anything about linking frontend to backend except that we need to use an APi.

  import React, { useState } from "react";
 import { v4 as uuidv4 } from "uuid";


 const ControlledInputs = () => {

 const [person, setPerson] = useState({
 firstName: "",
  email: "",
   age: "",
phoneNumber: "",
});
const [people, setPeople] = useState([]);

const handleChange = (e) => {
const name = e.target.name;
const value = e.target.value;
setPerson({ ...person, [name]: value });
};

const handleSubmit = (e) => {
e.preventDefault();
if (person.firstName && person.email && person.age && person.phoneNumber) {
  console.log(person);
  const newPerson = { ...person, id: uuidv4() };
  setPeople((person) => {
    return [...person, newPerson];
  });
  console.log(people);
 } else {
  console.log("error");
 }
  };

this where the form starts it's a simple form of 4 inputs return ( <> Name : Email : Age : Phone Number : add person {people.map((person) => { const { id, firstName, email } = person; return ( {firstName}

{email}

); })} </> ); };
             export default ControlledInputs;
question from:https://stackoverflow.com/questions/66046434/how-can-i-send-data-from-this-reactjs-form-to-a-database

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If it is RESTful API method, use axios to patch the data.

https://github.com/axios/axios

axios
  .post("/user", {
    firstName: person.firstName,
    ...
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...