1

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

Kirit Modi
  • 21,371
  • 13
  • 83
  • 108

2 Answers2

2

Correct - React hooks can only be called in the top-level body of a function component.

A better approach here would be to rewrite logoutFromApp as a Redux thunk, and then dispatch(logoutFromApp("abcd")) from within your component.

markerikson
  • 42,022
  • 7
  • 87
  • 109
2

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);
  }
};
Manoj Rawat
  • 106
  • 2
  • 7