TypeError: Cannot read properties of null (reading 'attributes')

Hi all. I am following a tutorial from Moralis YouTube channel titled “React & Moralis - Save User Data [Part 3]” and although I follow the exact steps, I have a problem when we’re trying to load a username when logging in using email & password.

I’ve googled and I learned that this is because the user.attributes.username is being called before the data is returned. However as a newbie to programming, I do not understand how to make it load after the data is ready.

I have also tried to follow instruction in this similar Moralis post but I do not know where to put the code being shared in that post.

Here is the error

**TypeError: Cannot read properties of null (reading 'attributes')**

App
src/App.js:12

 9 | if (isAuthenticated) {
  10 |   return (
  11 |     <Container>
> 12 |       <Heading>
     | ^  13 |         Welcome to the Twitter Clone, {user.attributes.username}
  14 |       </Heading>
  15 |       <Button onClick={() => logout()}>Logout</Button>

Here is the page code

import { Button, Container, Heading } from "@chakra-ui/react";
import { useState } from "react";
import { useMoralis } from "react-moralis";
import { Auth } from "./Auth";

function App() {
  const { isAuthenticated, logout, user } = useMoralis();

  if (isAuthenticated) {
    return (
      <Container>
        <Heading>
          Welcome to the Twitter Clone, {user.attributes.username}
        </Heading>
        <Button onClick={() => logout()}>Logout</Button>
      </Container>
    );
  }

  return (
    <Container>
      <Heading mb={6}> Welcome to the Twitter Clone</Heading>
      <Auth />
    </Container>
  );
}

export default App;

Fixed it by adding a check on the user data first before loading the user.attributes.username

{user && user.attributes.username}

2 Likes

Nice job!

Happy BUIDLing

1 Like