How to use ContextProvider function in the same file with <ContextProvider/>?

Viewed 90

I create a context for user authenticated.It like

interface IAuthContext{
    isAuthenticated:boolean
    setIsAuthenticated:Dispatch<SetStateAction<boolean>>
    checkAuth: () => Promise<void>
    logoutClient : () =>void,
}

const defaultIsAuthenticated = false
export const AuthContext = createContext<IAuthContext>({
    isAuthenticated:defaultIsAuthenticated,
    setIsAuthenticated: () =>{},
    checkAuth:() => Promise.resolve(),
    logoutClient : () =>{}
})

const AuthContextProvider= ({children} : {children:ReactNode}) =>{
    const [isAuthenticated,setIsAuthenticated] = useState(defaultIsAuthenticated)

    const checkAuth = async () =>{
        //check if token is existing
        const token = JwtManager.getToken()

        if(token) setIsAuthenticated(true)

        else{
            const success = await JwtManager.getRefreshToken()
            if(success) setIsAuthenticated(true)
        }
    }

    const authContextData = {
        isAuthenticated,
        setIsAuthenticated,
        checkAuth,
        logoutClient
    }
    return(<AuthContext.Provider value={authContextData}>
        {children}
    </AuthContext.Provider>)
}
export default AuthContextProvider

I use it in _app.tsx , but it not work. Whenever i move it to another component, it work. This is code in _app.tsx

function MyApp({ Component, pageProps }: AppProps) {
  const { checkAuth } = useContext(AuthContext);
  useEffect(() => {
    const authenticate = async () => {
      await checkAuth();
    };
    authenticate();
  }, []);
  return (
    <ApolloProvider client={client}>
      <AuthContextProvider>
        <ChakraProvider resetCSS theme={theme}>
          <Component {...pageProps} />
        </ChakraProvider>
      </AuthContextProvider>
    </ApolloProvider>
  );
}

export default MyApp;

I must use CheckAuth() in _app.tsx for user authenticated, so how can I solve this problem?

0 Answers
Related