V
V
Vadim2018-07-31 16:03:19
React
Vadim, 2018-07-31 16:03:19

How to validate API responses in redux (specifically react native)?

I will give an example of a standard action for accessing the API:

const loginStart = () => {
    return {
        type: AUTH_LOGIN
    };
};

const loginSuccess = (payload) => {
    return {
        type: AUTH_LOGIN_SUCCESS,
        payload: payload
    };
};

const loginFail = (payload) => {
    return {
        type: AUTH_LOGIN_FAIL,
        payload: payload
    };
};

export const login = (data) => (dispatch) => {
    dispatch(loginStart());

    return fetch(API_ENDPOINT, {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    })
        .then((response) => response.json())
        .then(
            (response) => {
                    dispatch(loginSuccess(response.response));
            }
        ).catch(
            (error) => {
                dispatch(loginFail(error));
            }
        );
};


There were a number of issues with request parsing and so on.
1) Should I trust the API and trust the data it returns?
Do I need to do type checks? or such check
if (response.status == 'success') {}
if (response.data) {} //убедиться что data точно есть

or the following check:
if (response.data.token && response.data.token.length > 0) {} // Удостоверимся что токен есть в ответе


2) How and where is it necessary to check responses from the server?
If the user has lost the Internet, then the request will return 500, is it necessary to process this in a mobile application?
If I do check the response from the server and it doesn't match my expectations, how do I handle these errors? Do throw new Error() ? And catch the same errors in catch, along with 500 400 errors?

3) In the general case, checks for 500 400 or for status from api request will be repeated, where should they be taken out?
Maybe a separate middleware or a separate service to write for this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim, 2018-07-31
@maxfarseer

I'll start from the end:
3) you can make a helper function, like check status,
I will give an example of code from an old project (not async / await, but not the point)

export function checkStatus(response) {
  let json = response.json() // http://stackoverflow.com/a/29475662/1916578

  if (response.status >= 200 && response.status < 300) {
    return json
  } else {
    return json.then(window.Promise.reject.bind(window.Promise))
  }
}

export function httpGet(url) {
  return fetch(url, {
    headers: buildHeaders(),
  })
  .then(checkStatus)
}

and already everywhere to use httpGet for getas, for example. Of course, you can expand the example as you need with the necessary dispatches and so on.
2) it is always necessary to check so that the user understands what is happening: -
probably your Internet has disappeared
- there is an error on the server, try again
I think you should start doing this in the catch for each request
necessary
If the API is yours, then checks also need to be done, but mainly it is necessary to handle errors from the server / network.

D
Dimka Reactive, 2018-08-17
@raoffonom

If you have a REST API, then learn Redux Saga
If GraphQL API, then Apollo Client is the best solution .
These libraries, among other things, are tailored to solve your problems.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question