Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing alert from service class in react-native

Tags:

react-native

I have an HTTP service class which is responsible for communication with my Laravel based API. I want the HTTP service class to trigger React Native Alert box when there is a 401 authentication issue. Or 403 Access denied issue or 422 which is validation issue.

I have the basic HTTP service class ready, but I am not able to show an alert from my HTTP service because it is not a react component and I want to know if I can use such a global service class and still trigger Native components.

Below is my code:

import axios from 'axios';
import {
  AsyncStorage,
  Alert
} from 'react-native';

class HttpService {
  async get(url) {
    let at = await AsyncStorage.getItem('access_token', (error, accessToken) => {
      return accessToken;
    });

    let data = await axios.get(url, {headers: { 'Authorization': 'Bearer ' + at }})
      .then(response => {
        console.log('response', response);
        return response;
      })
      .catch(error => {
        let message, title = '';

        if (!error.response) {
          message = error;
        }

        if (error.response.status === 401) {
          message = error.response.data.message;
          title = 'Authentication issue'
        }

        Alert.alert(title, message, [
          { text: 'Ok', onPress: () => console.log(123) }
        ]);
      });

    return data;
  }

  post() {}
}

export default HttpService;
like image 491
Amitav Roy Avatar asked Feb 27 '26 23:02

Amitav Roy


1 Answers

Why not just return the errors too? So you can determine what occurred so the component that makes the HttpService call knows when to show the Alert.

class yourComponent extends Component{

  constructor() {
    this.state = {
      token: null,
      isLoaded: false,
      error: null
    }
  }

  componentDidMount() {
    HttpService.get('someUrl')
      .then(res => {
        this.setState({
          token: res,
          isLoaded: true
        });
      }, (error) => {
        this.setState({
          error: error,
          isLoaded: true
        });
      })      
    }
  }

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      // return your Alert here
    } else if (!isLoaded) {
      // return loading component;
    } else {
      // return your main component
    }  
  }

}
like image 162
johnborges Avatar answered Mar 02 '26 15:03

johnborges



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!