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

Viewed 109

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 :)

1 Answers

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

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();
}, []);
Related