0

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

Shinne
  • 65
  • 8
  • Are you calling `usePostHog`? – Ben West Nov 05 '21 at 02:19
  • @BenWest yes. I called I did ```const posthog = usePostHog()``` – Shinne Nov 05 '21 at 02:23
  • You are accessing the context ***outside*** the context provider and didn't provide any default context value, thus the undefined access. – Drew Reese Nov 05 '21 at 02:31
  • @DrewReese what does this mean? Do I need to import posthog into my main.js? – Shinne Nov 05 '21 at 02:41
  • Oh, sorry, I misread what the code was doing in the first snippet. Please edit question to include all relevant code. What is `Main` component doing, and what are the reproduction steps to induce the error? – Drew Reese Nov 05 '21 at 02:45

1 Answers1

1

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.

Shinne
  • 65
  • 8