最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Next.js TypeError: Cannot read property '' of undefined when trying to console log api results - St

programmeradmin3浏览0评论

So this is kind of a weird error. What I'm trying to do in my Next.js app is to console log contents of an API call to see what I get. This API function just checks if a user is logged in and if so then I'll render a certain section of code. From my auth.js actions file which get a cookie that contains user info of a signed in user from local storage:

export const isAuth = () => {
if (process.browser) {
    const cookieChecked = getCookie('token');
    if (cookieChecked) {
        if (localStorage.getItem('user')) {
            return JSON.parse(localStorage.getItem('user'));
        } else {
            return false;
        }
    }
}

};

In my pages folder I have a file [username].js where right now I'm just trying to log a certain piece of information about the user in this instance the username:

{ isAuth().username ? console.log(isAuth().username)  : "" }

I'm even checking to make sure it's set however even then I get a TypeError: Cannot read property 'username' of undefined

However if I just log the entire user object { isAuth() ? console.log(isAuth()) : "" } it console logs just fine. Here's what is returned:

{
"_id": "5f7a39ab7acc30a29c5280df",
"username": "dylancougar",
"name": "Dylan Cougar",
"role": 2}

So all the info is there however when I try to isolate any info in the object I get the error. Even more strange is every once in a while if the offending bit code is mented out, and I unment it and save it will actually work sometimes, however, if I reload the page error returns. I'm not an expert on Next.js, so perhaps there is something obvious that I'm overlooking.

So this is kind of a weird error. What I'm trying to do in my Next.js app is to console log contents of an API call to see what I get. This API function just checks if a user is logged in and if so then I'll render a certain section of code. From my auth.js actions file which get a cookie that contains user info of a signed in user from local storage:

export const isAuth = () => {
if (process.browser) {
    const cookieChecked = getCookie('token');
    if (cookieChecked) {
        if (localStorage.getItem('user')) {
            return JSON.parse(localStorage.getItem('user'));
        } else {
            return false;
        }
    }
}

};

In my pages folder I have a file [username].js where right now I'm just trying to log a certain piece of information about the user in this instance the username:

{ isAuth().username ? console.log(isAuth().username)  : "" }

I'm even checking to make sure it's set however even then I get a TypeError: Cannot read property 'username' of undefined

However if I just log the entire user object { isAuth() ? console.log(isAuth()) : "" } it console logs just fine. Here's what is returned:

{
"_id": "5f7a39ab7acc30a29c5280df",
"username": "dylancougar",
"name": "Dylan Cougar",
"role": 2}

So all the info is there however when I try to isolate any info in the object I get the error. Even more strange is every once in a while if the offending bit code is mented out, and I unment it and save it will actually work sometimes, however, if I reload the page error returns. I'm not an expert on Next.js, so perhaps there is something obvious that I'm overlooking.

Share Improve this question asked Nov 27, 2021 at 3:11 JinjoeJinjoe 611 gold badge1 silver badge9 bronze badges 1
  • There might be a point when your page initially loads where isAuth() is returning undefined because of process.browser evaluating to false. When this happens you'll get your error. Try doing something like { isAuth() && isAuth().username ? console.log(isAuth().username) : "" } to make sure its not undefined before accessing the property. – deafening_roar Commented Nov 27, 2021 at 3:17
Add a ment  | 

1 Answer 1

Reset to default 2

The problem here is that next.js renders your data in the server first and process.browser is undefined in the server. So do the following:

  export const isAuth = () => {
  let user = false
  if (process.browser) {
    const cookieChecked = getCookie('token');
    if (cookieChecked) {
      if (localStorage.getItem('user')) {
        user = JSON.parse(localStorage.getItem('user'));
        return user;
      } 
    } 
  }
  return user;

This should work.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论