简体   繁体   中英

How to call function inside react native context provider

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>

in App.js file or your startup file

make sure you add the authProvider.

<AuthProvider> 
  <OtherProviders>
    <YourScreens />
  </OtherProviders>
</AuthProvider>
// 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM