Invalid hook call When Call useDispatch in global function?

Viewed 824

Code ::

import {Alert} from 'react-native';
import action from './../Redux/Actions/auth';
import {useDispatch, useSelector, useStore} from 'react-redux';
import AsyncStorage from '@react-native-async-storage/async-storage';

export const logoutFromApp = (message) => {
  if (
    message === 'Unauthorized!' ||
    message === 'Unactivite' ||
    message === 'No token provided!'
  ) {
    Alert.alert(
      'App',
      'Your account is deactivated or unauthorized, please try again to login.',
      [
        {
          text: 'ok',
          onPress: () => {
            AsyncStorage.clear();
            const dispatch = useDispatch();
            dispatch(action.logout());
          },
        },
      ],
    );
  } else {
    alert(message);
  }
};

Error :

enter image description here

2 Answers

If you want to use dispatch in a non react function you can use store.dispatch()

import {store} from "location of store" 
export const logoutFromApp = (message) => {
  if (
    message === 'Unauthorized!' ||
    message === 'Unactivite' ||
    message === 'No token provided!'
  ) {
    Alert.alert(
      'App',
      'Your account is deactivated or unauthorized, please try again to login.',
      [
        {
          text: 'ok',
          onPress: () => {
            AsyncStorage.clear();
            
           store.dispatch(action.logout());
          },
        },
      ],
    );
  } else {
    alert(message);
  }
};
Related