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

234
Visualizações
JavaScript using async/await to make sure I retrieve value before implementation, but still get 'undefined' returned

Code

async function getStudents() {
  var reqObj = new RequestHandler("/students/all/");
  let { students } = await reqObj.sendRequest();
  console.log(students, students.length);
  return students;
}

export default function Students(props) {
  var students = getStudents();
  return (
    <main className="content-section">
      <h1>Students</h1>
      <span className="help-text">
        You have {`${students.length}`} students.
      </span>
    </main>
  );
}

...

export class RequestHandler {
  // Base class for handling requests
  constructor(url, method = "GET", contentType = "application/json") {
    this.url = url;
    this.method = method;
    this.contentType = contentType;
    this.request_conf = {
      method: this.method,
      url: this.url,
      headers: {
        "Content-Type": this.contentType,
        "X-CSRFToken": cookies.get("csrftoken"),
      },
      credentials: "same-origin",
    };
  }
  async sendRequest() {
    const response = await axios(this.request_conf);
    var data = isResponseOK(response);
    return data;
  }
}

The console.log(students, students.length); within the getStudents() function gives me the output just as I expect: [] 0, but despite trying to make it an asynchronous function and all, the Students component still get undefined as value back. What would be the easiest way to get the same value read within the Students component?

DISCLAIMER

I am a beginner at JavaScript and especially Promises, so if there's something really simple and/or obvious that I am missing here, please tell me so and don't be toxic about it :)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The "render" function of React is a synchronous, pure function. It can't wait for values to be rendered. This is what lifecycle methods and state are for.

Use useState hook to hold the students array in state, and an useEffect hook with empty dependency array to make the call to getStudents and await for the Promise to resolve and enqueue a state update and trigger a rerender.

export default function Students(props) {
  // state to hold values
  const [students, setStudents] = React.state([]);

  // effect to fetch values
  React.useEffect(() => {
    getStudents().then(students => setStudents(students));
  }, []); // <-- empty dependency == run once on component mount

  return (
    <main className="content-section">
      <h1>Students</h1>
      <span className="help-text">
        You have {`${students.length}`} students.
      </span>
    </main>
  );
}

Docs

  • useState
  • useEffect

If you prefer async/await to Promise chains:

React.useEffect(() => {
  const fetchStudents = async () => {
    try {
      const students = await getStudents();
      setStudents(students);
    } catch(error) {
      // handle error, log it, etc...
    }
  };
  fetchStudents();
}, []);
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