0

I'm getting the error "Cannot destructure property 'currentUser' of 'Object(...)(...)' as it is null" when I use useContext() hook from react in Next.js.

// Other imports
import CurrentUserContext from "../../contexts/current-user/current-user.context";

class Layout extends React.Component {
  constructor() {
    super();
    this.state = {
      currentUser: null,
    };
  }

  unsubscribeFromAuth = null;

  componentDidMount() {
    // Auth code
  }

  componentWillUnmount() {
    // unsubscribe code
  }

  render() {
    const { children, title } = this.props;
    return (
      <React.Fragment>
        <Head>
          <title>{title}</title>
        </Head>
        <CurrentUserContext.Provider value={this.state.currentUser}>
          <Header />
        </CurrentUserContext.Provider>
        {children}
        <Footer />
      </React.Fragment>
    );
  }
}

export default Layout;

Here is where the error happens

// Other imports
import CurrentUserContext from "../../contexts/current-user/current-user.context";
import { useContext } from "react";

const Header = () => {
  const { currentUser } = useContext(CurrentUserContext);
  return (
    // Header Jsx
  );
};

export default Header;

This is how I created the context file

import { createContext } from "react";

const CurrentUserContext = createContext(undefined);

export default CurrentUserContext;

Error screenshot below Cannot destructure property 'currentUser' of 'Object(...)(...)' as it is null

Any help is appreciated.

Joseph D.
  • 11,804
  • 3
  • 34
  • 67

2 Answers2

2

The initial value of your context is just null and there's no key currentUser in your context.

this.state = {
  currentUser: null,
};

<CurrentUserContext.Provider value={this.state.currentUser}> // just null

To be able to destructure a currentUser in your context, you could do:

<CurrentUserContext.Provider
  value={{
    currentUser: this.state.currentUser
  }}
>
Joseph D.
  • 11,804
  • 3
  • 34
  • 67
  • 1
    Also this link make sure context is wrapping in correct location https://ankurraina.medium.com/reactjs-pass-functions-through-context-typeerror-cannot-destructure-property-of-450a8edd55b6 – smile Jan 27 '22 at 00:26
1

Your context value isn't an object to destructure, it's simply a value (currently null), i.e. the context value is simply the value of this.state.currentUser, not {currentUser: this.state.currentUser }. You can just access it directly, no destructuring necessary.

// Other imports
import CurrentUserContext from "../../contexts/current-user/current-user.context";
import { useContext } from "react";

const Header = () => {
  const currentUser = useContext(CurrentUserContext); // <-- Remove the curly brackets
  return (
    // Header Jsx
  );
};

export default Header;
Drew Reese
  • 165,259
  • 14
  • 153
  • 181