-1

I would like to stop a request when the database is offline or when there is a problem with the backend conexion, but I don't know how to do this.

My Axios settings are as follows:

import axios from "axios";
import AsyncStorage from '@react-native-async-storage/async-storage';

const baseURL = 'http://192.168.1.43:4000/server';

const gestorMedicoApi = axios.create({ baseURL});

gestorMedicoApi.interceptors.request.use(
    async (config) => {
        const token = await AsyncStorage.getItem('token');
        if (token) {
            config.headers!['x-token'] = token;
        }

        return config;
    }
)
export default gestorMedicoApi;

And an request example is the following:

    const signUp = async ({ nombreEmpresa, email, telefono, contraseña }: RegisterData)  => {
        try {
            const resp = await gestorMedicoApi.post<Response>('/user/createUser', { nombreEmpresa, email, telefono, contraseña }); 

            dispatch({
                type: 'signUp',
                payload: {response: resp.data}
            })

        } catch (error: any) {
            dispatch({ type: 'addError', payload: {response: {status: "NOK", message: "Se ha producido un error al conectar con la base de datos."}} })
        }
    };

If the next line fails:

 const resp = await gestorMedicoApi.post<Response>('/user/createUser', { nombreEmpresa, email, telefono, contraseña });

The flow go into the catch, but the request tries to conect again and again, so I would like to stop the request if it fails.

How can I get it?

Victor
  • 253
  • 2
  • 3
  • 12
  • 2
    *"...but the request tries to conect again and again..."* What code is doing that? Axios itself won't repeat the request. Whatever code is doing that repeat is the code you have to fix/change, not axios. – T.J. Crowder Jan 23 '22 at 11:12
  • 1
    You can use AbortController, example and docs here https://axios-http.com/docs/cancellation – Eduard Jan 23 '22 at 11:15
  • You can find answer here [Check this](https://stackoverflow.com/questions/38329209/how-to-cancel-abort-ajax-request-in-axios) – UI_Brain Jan 23 '22 at 11:39

1 Answers1

0

axios doesn't make repetitive requests. It is possible that your component is being re-rendered or is stuck in a loop which is calling your sign-up function continously. Please re-check your code and if possible provide more snippets.

amit.s19
  • 193
  • 10