How to access Context within a Class Component for react native?

I want to use my Context in a class component (MyEventsScreen), but whenever I do so, I get an error saying it is an invalid hooks call.

Here is MyEventsScreen.js (I’ve simplified it to be brief):

import { useAuthState } from "../contexts/authContext";

export default class MyEventsScreen extends Component {

 render() {
    return (
      <View>
          <Text></Text>
      </View>
}

I have my authContext.js here:

import React from "react";
import { authReducer } from "../reducers/authReducer";

const AuthStateContext = React.createContext();
const AuthDispatchContext = React.createContext();

function AuthProvider({ children }) {
  const [state, dispatch] = React.useReducer(authReducer, {
    isLoading: true,
    isSignout: false,
    userToken: null,
    email: null,
    userID: null,
  });

  return (
    <AuthStateContext.Provider value={state}>
      <AuthDispatchContext.Provider value={dispatch}>
        {children}
      </AuthDispatchContext.Provider>
    </AuthStateContext.Provider>
  );
}

function useAuthState() {
  const context = React.useContext(AuthStateContext);
  if (context === undefined) {
    throw new Error("useAuthState must be used within a AuthProvider");
  }
  return context;
}
function useAuthDispatch() {
  const context = React.useContext(AuthDispatchContext);
  if (context === undefined) {
    throw new Error("useAuthDispatch must be used within a AuthProvider");
  }
  return context;
}

export { AuthProvider, useAuthState, useAuthDispatch };

I have an authReducer.js here:

export const authReducer = (prevState, action) => {
  switch (action.type) {
    case "SIGN_IN":
      return {
        ...prevState,
        email: action.email,
        isSignout: false,
        userToken: action.token,
      };
    default:
      return prevState;
  }
};

Any help would be appreciated!

Answer

For class components you can use the Consumer provided by the context .

export your AuthStateContext

export const AuthStateContext = React.createContext();

In the class component you can use it as

import { useAuthState, AuthStateContext } from "../contexts/authContext";

export default class MyEventsScreen extends Component {
  render() {
    return (
      <AuthStateContext.Consumer>
        {(value) => { // read the context value here 
          return (
            <View>
              <Text></Text>
            </View>
          );
        }}
      </AuthStateContext.Consumer>
    );
  }
}

Reference

Context Consumer