How to use React.useContext(AuthContext) inside a class component to trigger a condition set in index.js file

Viewed 2048

My project file code snippets are as follows Index.js

import { AuthContext } from './components/context';
const Drawer = createDrawerNavigator();
export default function App() {

  const [isLoading, setIsLoading] = useState(true);
  const [userFound, setUserFound] = useState(false);
   
  
  const authContext=React.useMemo(()=>({     
    skipOn:async() =>{      
     setSkip(true);
    
    },
    skipOff:async()=>{
      setSkip(false);
    }
  }),[])

 
  return (


    <AuthContext.Provider value={authContext}>
    <NavigationContainer >
      { (userFound || skip) ? (<Drawer.Navigator
        drawerContent={props => <DrawerContent {...props} />}
        headerMode='none'
        screenOptions={{
          header: () => (null)
        }}>
        <Drawer.Screen name="HomeDrawer" component={HomeStackScreen} />
        <Drawer.Screen name="OfferDrawer" component={OfferStackScreen} />

      </Drawer.Navigator>) : <LoginStackScreen/>}

    </NavigationContainer>
    </AuthContext.Provider>

  );
}

when user tries to login , if he chooses to skip the process, he will trigger the skipOn() method. skipOff() would land the user back to login screen. I want to access skipOff in a HomeStackScreen component on button press .Below is the code snippet. How to access the authcontext inside class component


class CardItemDetails extends Component {

  constructor(props) {
    super(props)

    this.state = {
      isFavorite: false,
      item: { isLoading: true, errMess: null, item: null, discount: null }
    }
  }
  orderNowHandler = () => {
    if (currentuser is authenticated) {
      
           navigate to another screen
    }
    else {
      trigger skipOff() and land on login page
  }

I am always getting invalid hooks call exception while trying to invoke skipOff(). What is the correct way of invoking/implementing this scenario?

1 Answers

To consume a context inside class component, you can assign a contextType to read the current context. Using contextType lets you consume the nearest current value of that Context type using this.context. You can reference this in any of the lifecycle methods including the render function.

So, you can write:

import { AuthContext } from './components/context';

class CardItemDetails extends Component {
  static contextType = AuthContext // assign static contextType
  constructor(props) {
    super(props)
    this.state = { ...code here... }
  }

  orderNowHandler = (e) => {
    if (writeYourConditionHere) {
      this.context.skipOn() // consume the context values or functions
    } else {
      this.context.skipOff()
    }
  }

Also, see the hook useContext which lets you consume context values in function components.

PS: You cannot use React.useContext(AuthContext) inside a class component because hooks (useContext here) can only be used in a function component.

Related