Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

72
Visualizações
State doesn't update immediately in React

I know I have to use useEffect but I couldn't figure out a way to make this code to work. I want the state courses to be updated immediately every single time I'm adding a new course. The data variable in the getCourses function is updated, but the update of the state doesn't happen immediately.

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

this function gets the list of courses from the database and store it in courses

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
}

this function adds a course and then adds the professor stored in idProf to this course

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);
}

I tried to use useEffect but it s updating the state only one time

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

the courses are not updated when this function is running

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 Respostas
Responde à pergunta

0

Your getCourses funciton is async, but you are not awaiting it. Try await getCourses().

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda