MARodriguez
MARodriguez

Reputation: 21

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(() => {
    API.getStudentDetails(params.studentId).then(setStudent);
},[student]);




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

return(
    <>
        <div>Editar alumno {student.dni}</div>
        <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>
            </form>
        </div>
    </>
)

How can do this? Thanks in advance

Upvotes: 0

Views: 125

Answers (1)

Bernhard Josephus
Bernhard Josephus

Reputation: 715

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(() => {
    API.getStudentDetails(params.studentId).then(setStudent);
},[]);

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

useEffect(() => {
    API.getStudentDetails(params.studentId).then(setStudent);
},[params.studentId]);

Upvotes: 2

Related Questions