Passing function into context in react-native using typescript

Viewed 79
const AuthContext = React.createContext<any>({ currentUser: null, signUp: null});

export function useAuth() {
    return useContext(AuthContext);
}

export function AuthProvider({ children }) {
  const [ currentUser, setCurrentUser ] = useState<any>();

  function signUp(email?: string, password?: string){
    if (email && password && email.length > 3 && password.length > 5){
      return auth.createUserWithEmailAndPassword(email, password);
    } 
    return auth.signInWithPopup(googleAuthProvider);
  }

  useEffect(() => {
      const unsubscriber = auth.onAuthStateChanged( user => {
          setCurrentUser(user);
          })

      return unsubscriber;
      }, [])

  const value = {
    currentUser,
    signUp,
  }

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

This is how i imported, deconstructed and used

import {useAuth} from "./{some-path}/AuthContext";

function SignUp() {
 const { signUp } = useAuth();

 function insideSomeFunction(){
   signUp!();
 }

 return (
 {simple react-nataive componenst to call insidesomefunction}
 )
}

Problem is whenever I try to use signUp by importing useAuth and deconstructing it to get signUp function, it always give null, even tho I have provided the implementation in the AuthProvider function.

  • I am new to react-native and using context in react
3 Answers

undefined value is error prone. So, initialize user with null:

const [ currentUser, setCurrentUser ] = useState<any>(null);

Make sure that you are wrapping the All Childs in the AuthProvider component so we can access the context in our children.

Like:

<AuthProvider>
  <Child />
</AuthProvider>

And using the useAuth context in the Child Component.

AuthContext implementation is correct. Make sure you wrapped the entire app with AuthProvider.

export default function App(): ReactElement {
    return (
        <AuthProvider>
                   // I belive your app has  a navigator         
                    <Navigator />             
        </AuthProvider>
    );
}
Related