Gokul Sajan
Gokul Sajan

Reputation: 383

Rest API axios error handling in redux-saga using catch

On inspecting in Chrome in the network tab, I get this response:

{"status":"error","data":{"message":"Unauthorized"}} 

Is there any issue in catching an axios error? How should I handle this issue? I get a succesful response on authorised login.


Redux-Saga Generator function


export function* loginUserSaga(action) {
  yield put(actions.loginStart());
  const loginData = {
    'email': action.email,
    'password': action.password
  };
  let url ="api/v1/login";
  console.log("Saga-send:",loginData);
  try {
    const response = yield axios.post(url, loginData);
    console.log("Saga-recived:",response);
    yield localStorage.setItem("token", response.data.data.access_token);
    yield put(
      actions.loginSuccess(response.data.idToken)
    );
  } catch (error) {
    console.log("Saga-error:",error);  
    yield put(actions.loginFail(error));
  }
}

Console


Saga-send: {email: "[email protected]", password: "assasaassasa"} 
Saga-error: Error: Request failed with status code 401
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:60)

also gets an error on axios.post()

Upvotes: 3

Views: 3517

Answers (1)

Sadidul Islam
Sadidul Islam

Reputation: 1348

import Api from './path/to/api'
import { call, put } from 'redux-saga/effects'

function fetchProductsApi() {
  return Api.fetch('/products')
    .then(response => ({ response }))
    .catch(error => ({ error }))
}

function* fetchProducts() {
  const { response, error } = yield call(fetchProductsApi)
  if (response)
    yield put({ type: 'PRODUCTS_RECEIVED', products: response })
  else
    yield put({ type: 'PRODUCTS_REQUEST_FAILED', error })
}

Here is the Documentation

Upvotes: 3

Related Questions