React JS Context, TypeError: Cannot read properties of undefined

1.6k Views Asked by At

I'm pretty new to JS and React JS so some help would be really appericated.

Im trying to create a context for this import 'posthogs'. I made a context file and I added the and surrounded on of my main

PostHogContext.js

import posthog from "posthog-js";
import React, { useContext, useEffect, useState } from "react";

const PostHogContext  = React.createContext();

export function usePostHog(){
    return useContext(PostHogContext);
}

export default function PostHogContextProvider({ children }) {

    const [initPostHog,setInitPosthog] = useState(posthog)

    useEffect(() => {
            console.log("Initializing PostHog");
            setInitPosthog(posthog.init());
    },[initPostHog]);

    return(
        <PostHogContext.Provider value={initPostHog}>
            {children}
        </PostHogContext.Provider>
    )
}

export { PostHogContext };

Surrounded the context provider with main

<PostHogContextProvider>
  <Main>
</PostHogContextProvider>

When I call it in my from my main.js

function MainPage(props){

posthog.identify(user.email);

}

I get this error that says

TypeError: Cannot read properties of undefined (reading 'identify')

from what I can see it doesn't seem like it found the posthog.identify function or the posthog value is null but i'm not sure why that is when I set it in the provider

1

There are 1 best solutions below

0
Shinne On

Okay I figured it out, first

my setState has a typo.

const [initPostHog,setInitPosthog] = useState(posthog)

initPostHog and setInitPosthog. So my value wasn't getting set correctly.