Cannot destructure property ‘currentUser’ of ‘Object(…)(…)’ as it is null

Total
1
Shares

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.


Solution

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
  }}
>
Leave a Reply

Your email address will not be published. Required fields are marked *