0

I have a question, how to translate errors which are catch in redux-saga. How are you doing it in React-Redux?

I am trying to do it like this:

catch (error) {
  if(error.response.payload.error==='Unauthorized'){
        Alert.error(<FormattedMessage {...messages.unauthorizedMessage} />, {
          html: false,
        });
  }
PrEto
  • 395
  • 2
  • 7
  • 23

1 Answers1

1

In the saga catch block, dispatch an action:

// saga:
catch(error) {
  if(error.response.payload.error==='Unauthorized'){
    yield put({ 
      type: 'UNAUTHORIZED_REQUEST',
      message: messages.unauthorizedMessage
    })
  }
}

Then in a reducer, update state based on the action:

const requestError = (state = null, { type, messageĀ }) => {
    case 'UNAUTHORIZED_REQUEST':
        return message;
    default:
        return state;
}

Then, have a component render the error message to reflect the updated state:

let MyComponent = ({ requestError }) => {
    return (
        <div>
            {requestError &&
                <MyErrorMessage message={requestError} />
            }

            {/* ... */}
        </div>
    )
}

MyComponent = connect(
    state => ({
        requestError: state.requestError
    })
)(MyComponent)
brietsparks
  • 4,776
  • 8
  • 35
  • 69