0

I am trying to implement useContext in my react-native app but getting an error as: "undefined is not an object (evaluating 'context._context')".

here is my code(Trying to use the EmailContext):

import React, {useState} from 'react';

export const Emailcontext = React.createContext("");

const ContextStore = ({children}) => {
    const [emailAddress, setEmailAddress] = useState("");

    return(
        <Emailcontext.Provider value={[emailAddress, setEmailAddress]}>
            {children}
        </Emailcontext.Provider>
    );
}

export default ContextStore;

And here I wrap my app with the ContextStore:

    <ContextStore>
      <NavigationContainer>
        <Stack.Navigator 
          screenOptions={{headerShown: false}}
        >
          <Stack.Screen name='EmailVerification' component={EmailVerification} />
          <Stack.Screen name='VerifyEmailExplenation' component={VerifyEmailExplenation} />
        </Stack.Navigator>
      </NavigationContainer>
    </ContextStore>

And then the context is undefined in this component:

import React, {useContext, useState} from 'react';
import {EmailContext} from '../ContextStore'

const EmailVerification = ({navigation}) => {
    const [emailAddress, setEmailAddress] = useContext(EmailContext);
  
    return(
      **jsx element**
    );
}
export default EmailVerification;

Cant find any solution for that..

Omer Ohana
  • 3
  • 1
  • 3
  • Is this all just the typo, where you're exporting as `Emailcontext` but importing as `EmailContext`? – Jacob Nov 05 '20 at 23:06

1 Answers1

1

I was mistaken you are importing EmailContext it should be Emailcontext Your Email Verification component should look like this:

import React, {useContext, useState} from 'react';
import {Emailcontext} from '../ContextStore'

const EmailVerification = ({navigation}) => {
    const [emailAddress, setEmailAddress] = useContext(Emailcontext);
  
    return(
      **jsx element**
    );
}
export default EmailVerification;

also you have made ContextStore a default export so when importing into your app.js ensure you are importing it like so:

import ContextStore from '...correct path'

I know you are using react-native but here is a code pen of a CRA, where I wrap the index.js in the provider and do the proper imports into app.js to emulate your EmailVerification component.

https://codesandbox.io/s/admiring-shaw-5yrs3?file=/src/App.js

Rob Terrell
  • 2,398
  • 1
  • 14
  • 36