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;
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);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.