Edit form with api data in react

I have a form in react that is filled with data from an api. I want to edit this data in the form, but i can not do it, because api always overwrite the fields.

This is my code:

let params = useParams();

const [student, setStudent] = useState([]);

useEffect(() => {

function editStudent(){
    API.editStudent(student).then(result => {
        if (result){
            alert("Estudiante modificado");

        <div>Editar alumno {student.dni}</div>
            <form id="formulario">
                ID<input type='text' id='id' disabled value={student.id} /> <br />
                DNI<input type='text' id='dni' value={student.dni} onChange={event => setStudent({...student, dni:event.target.value})} /><br />
                Nombre<input type='text' id='nombre' value={student.nombre} onChange={event => setStudent({...student, nombre:event.target.value})} /><br />
                Dirección<input type='text' id='direccion' value={student.direccion} onChange={event => setStudent({...student, direccion:event.target.value})}/><br />
                Edad<input type='number' id='edad' value={student.edad} onChange={event => setStudent({...student, edad:event.target.value})}/><br />
                Email<input type='text' id='email' value={student.email} onChange={event => setStudent({...student, email:event.target.value})}/><br />
                <button id='editar' onClick={() => editStudent()}>Editar</button>

How can do this? Thanks in advance

>Solution :

The problem is with your useEffect hook. The useEffect will be called every time the student state is changed. You call setStudent on every form field changes which will trigger the useEffect which at the end will get the initial student data from the api.

What you can do is to remove the student from the useEffect array of dependencies.

useEffect(() => {

With this, the useEffect will only be called when the component mount, or you can put params.studentId into the array if needed.

useEffect(() => {

Leave a Reply