Cannot read property 'code' of undefined from promise, context api (react hook)

I am making my first hybrid web app using react hook.
I am faced with a timing problem with promise and context api.

Here are the logic I am facing with.

  1. A function fetchApplications gets data from firebase firestore, it is defined in globalcontext.js (called in tableView)
  2. tableView.js calls fetchApplications in useEffect.
  3. fetchApplications is defined as promise function, I expect it will resolve(return) data until data fetched, it will resolove(return) object like {code:200, data:data}

in the fetchData.code,

Cannot read property ‘code’ of undefined

Here is my code

In the tableview.js

  React.useEffect(() => {
      context.fetchApplications(auth.userId, "")
      .then(function (fetchData) {
      console.log("Fetched data: ", fetchData);   ///this is undefined
      if (fetchData.code !== 200) {               /// error part
      if (! {
        alert("No applications");
  }, []);

In the GlobalContext.js

async function fetchApplications(userId, role) {
    return new Promise((resolve, reject) => {
      // resolve({ code: 200, data: "data" });     //If I add this code, it will be alright.

      let dataArray = [];
      let applicationRef = db
        .then(function (qs) {
          qs.forEach(function (doc) {             //doesn't work
            console.log(, " => ",;
            console.log(doc.size, " => ", typeof doc);
          return Promise.resolve(dataArray);
        .then((data) => {
          console.log("Global, Fetched Data", dataArray);
          if (data) {
            resolve({ code: 200, data: data });
    }).catch(function (error) {
      reject({ code: 400, msg: "시스템에러 고객센터에 문의해주세요" });

wrote in codesendbox
If I was write the wrong way of promise, please let me know.

18 thoughts on “Cannot read property 'code' of undefined from promise, context api (react hook)”

Leave a Comment