Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

70
Views
El estado no se actualiza inmediatamente en React

Sé que tengo que usar useEffect pero no pude encontrar una manera de hacer que este código funcione. Quiero que los cursos estatales se actualicen inmediatamente cada vez que agregue un nuevo curso. La variable de datos en la función getCourses se actualiza, pero la actualización del estado no ocurre de inmediato.

 function CourseList() { const [courses, setCourses] = useState([]); const [idProf, setIdProf] = useState();

esta función obtiene la lista de cursos de la base de datos y la almacena en cursos

 const getCourses = async () =>{ const response = await fetch(`${SERVER}/api/courses`); const data = await response.json(); setCourses(data); // -> here setCourses doesnt update the state, but data has the updated array of courses }

esta función agrega un curso y luego agrega el profesor almacenado en idProf a este curso

 const addCourse = async(course) => { //...fetch with post method...// getCourses(); // here i call the method but when I'm trying to add the professor to the course on the next line, the state isn't updated yet addStudentCourse(idProf, course.cod); }

Traté de usar useEffect pero está actualizando el estado solo una vez

 useEffect(()=>{ getCourses(); },[]);

los cursos no se actualizan cuando se ejecuta esta función

 const addStudentCourse = async(idStudent,codCourse)=>{ let id = -1; //searching for the id in courses for(let c of courses){ if(c.cod == codCourse){ id = c.id; } } console.log(id)// id is still -1, it cant find the course because the state wasnt updated yet if(id != -1){ //..adding to the database..// } } return (<div></div>)

}

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Su función getCourses es asíncrona, pero no la está esperando. Intente await getCourses() .

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!