Home > Software design >  Cannot read property of 'watchlist' undefined
Cannot read property of 'watchlist' undefined

Time:05-02

 authenticate(request, response) {
    const user = userstore.getUserByEmail(request.body.email);
    if (user) {
      response.cookie('watchlist', user.email);
      logger.info('logging in'   user.email);
      response.redirect('/start');
    } else {
      response.redirect('/login');
    }
  },

 getCurrentUser (request) {
  const userEmail = request.cookies.watchlist;
  return userstore.getUserByEmail(userEmail);
  }
} 

Here the code authenticates a user and up above it defines 'watchlist' as a cookie, however it keeps telling me it is undefined. How do I fix this?

CodePudding user response:

getUserByEmail is probably an async function. Be sure use await to make sure that we wait for the promise to resolve and return a value before moving to the next line. In your case it will look like this:

 async authenticate(request, response) {
    const user = await userstore.getUserByEmail(request.body.email);
    if (user) {
      response.cookie('watchlist', user.email);
      logger.info('logging in'   user.email);
      response.redirect('/start');
    } else {
      response.redirect('/login');
    }
  },

 async getCurrentUser (request) {
  const userEmail = request.cookies.watchlist;
  return await userstore.getUserByEmail(userEmail);
  }
} 

Further reading: JavaScript Async Await

  • Related