React Native – Error handler (1)

What network error may app have?

Error types

  • No connection
  • Timeout
  • 4XX Client Error
  • 5XX Server Error
    • 503 Service Unavailable

How to replicate API request?

const carsDB = {
  honda: { name: "civic", color: "black"},
  mazda: { name: "cx-3", color: "red"}
};

export function getCar(type) {
  return new Promise(resolve => {
    // simulate a fetch call
    setTimeout(() => {
      resolve(carsDB[type]);
    }, 1000);
  });
}

Network error handler with Axios

// Create HOC component
const AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 1000,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json; charset=utf-8',
  },
});

export const CheckRequests = (Wrapped) => {
  const Check = (props) => {
    useEffect(() => {
      AxiosInstance.interceptors.response.use(
        function (response) {
          // Do something with response data
          return response;
        },

        function (error) {
          switch (error.response.status) {
            case 503:
              console.log(error);
              break;
            default:
              break;
          }

          // Do something with response error
          return Promise.reject(error);
        }
      );
    });

    return <Wrapped {...props} />;
  };

  return Check;
};
// Usage
import React from "react"
import CheckRequests from "./HOC/CheckRequests"

function App(props){ ... }

export default checkRequests(App)

Then, call AxiosInstance when GET/ POST data

ErrorBoundary

Create ErrorBoundary component

import React from 'react';
import { ErrorView } from 'src/components';

export class ErrorBoundary extends React.Component<any, any> {
  state = {
    error: false,
  };

  static getDerivedStateFromError(error) {
    return { error: true };
  }

  componentDidCatch(error, errorInfo) {
    // deal with errorInfo if needed
  }

  render() {
    if (this.state.error) {
      return <ErrorView />;
    } else {
      return this.props.children;
    }
  }
}

export default ErrorBoundary;

Wrap app component with ErrorBoundary component

/**
 * @format
 */

import React, { useEffect } from 'react';
import { AppRegistry } from 'react-native';
import App from './src/App';
import { name as appName } from './app.json';
import { RecoilRoot } from 'recoil';
import ErrorBoundary from 'src/screens/error';

const MainApp = () => {
  return (
    <ErrorBoundary>
      <RecoilRoot>
        <App />
      </RecoilRoot>
    </ErrorBoundary>
  );
};

AppRegistry.registerComponent(appName, () => MainApp);

How to display an error screen with a Refresh button?

const ErrorView = () => {
  const navigation = useNavigation()

  const onRefresh = () => {
    refreshByNavigation(navigation)
  }

  return (
    <RefreshButton onRefresh={onRefresh} />
  )
}
const refreshByNavigation = (navigation) => {
  const state = navigation.getState()
  const routes = state.routes.map(element => {
    return {
      ...element
    }
  })

  routes[routes.length - 1].key = Math.random().toString()
  navigation.reset({
    ...state,
    routes
  })
}

export default refreshByNavigation

Be the first to comment

Leave a Reply

Your email address will not be published.


*