Home > database >  TypeError: Cannot read property 'signIn' of undefined
TypeError: Cannot read property 'signIn' of undefined

Time:11-06

const SignIn = ({navigation}) => {

const [data, setData] = React.useState({
    username: '',
    password: '',
    check_textInputChange: false,
    secureTextEntry: true,
    isValidUser: true,
    isValidPassword: true,
});

const { colors } = useTheme();

const { signIn } = React.useContext(AuthContext);
.
.
const loginHandle = (userName, password) => {
.
.
  signIn(foundUser);
}

In the above set of lines of code to implement SignIn in my react-native app, facing the error as mentioned in the title above i.e., TypeError: Cannot read property 'signIn' of undefined

CodePudding user response:

In your case first wrap the "SignIn" comp with "AuthContext" provider and pass the "signIn" function inside the value of the provider. I have given an example below.

import React,{createContext} from "react";

export const AuthContext = createContext();

/*Wrap the SignIn component with the contex provider and 
pass the "Login" function to value */

const AuthScreen = () =>{
  const Login = () =>{
    return(
      /* write your code */
    )
  }
  return(
    <AuthContext.Provider value={{signIn: Login}}>
       <SingIn />
    </AuthContext.Provider>
  )
}
export default AuthScreen

After that import the "AuthContext" and use the context by providing it inside the useContext and de-structure the context. Below I have re-write your code to provide an example.

import React,{useContext} from "react";
import {AuthContext} from './App.js'
const SignIn = ({navigation}) => {
  
  
  const { signIn } = useContext(AuthContext);

  return(
    /* your code */
  )

}

export default SignIn

CodePudding user response:

The following change of code worked:

const SignIn = ({navigation}) => {

const [data, setData] = React.useState({
    username: '',
    password: '',
    check_textInputChange: false,
    secureTextEntry: true,
    isValidUser: true,
    isValidPassword: true,
});

const { colors } = useTheme();

const { signIn } = React.createContext();
.
.
const loginHandle = (userName, password) => {
.
.
  signIn(foundUser);
}
  • Related