Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

231
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda