Home > Back-end >  How to call function inside react native context provider
How to call function inside react native context provider

Time:09-04

I have the below file and I am trying to call setAuthState however I can't seem to figure out how to call this function from another file. This context file is content from a mix of online sources with my changes so I think it should work but I am unsure how to call it properly. Everything I find when searching SO and Google is calling the function from inside the context provider like I am already doing inside useEffect.

I tried importing it as below

screen.js

import useAuth from '../../context/useAuth'
const { setAuthState } = useAuth();

then using it as

setAuthState(credentials)

Files with the actual code

useAuth.js

import { useContext } from 'react';
import AuthContext from 'auth.js';

export default () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('Error message: <tbd>');
  }
  return context;
}

auth.js

import React, { createContext, useState, useEffect } from 'react';
import { globalStorage } from '../state/global'

const AuthContext = createContext();

const AuthProvider = ({ children }) => {
  const [auth, setAuth] = useState(null);

    const checkAuth = () => {
      try {
        // do stuff
      } catch(e) {
        console.error(e)
      }
    }

  const setAuthState = data => {
    try {
      // do stuff
      setAuth(data);
    } catch (err) {
      console.error(err);
    }
  };

  useEffect(() => {
    checkAuth();
  }, []);

  return (
    <AuthContext.Provider value={{ auth, setAuthState}}>
      {children}
    </AuthContext.Provider>
  );
};

export { AuthProvider };

export default AuthContext;

Edit ** code response to an answer

<NavigationContainer>
      <AppProvider>
          <AppNavigation></AppNavigation>
        <FlashMessage position="bottom" />
      </AppProvider>
</NavigationContainer>

CodePudding user response:

in App.js file or your startup file

make sure you add the authProvider.

<AuthProvider> 
  <OtherProviders>
    <YourScreens />
  </OtherProviders>
</AuthProvider>

CodePudding user response:

// authContext.js
let authContext = createContext({
  auth: null,
  setAuth(credentials) {},
});
// useAuthHook.js
let useAuth = () => {
  let data = useContext(authContext);
  return data;
};
// App.js
let { auth, setAuth} = useAuth()
  • Related