Answer the question
In order to leave comments, you need to log in
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));
}
);
};
if (response.status == 'success') {}
if (response.data) {} //убедиться что data точно есть
if (response.data.token && response.data.token.length > 0) {} // Удостоверимся что токен есть в ответе
Answer the question
In order to leave comments, you need to log in
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)
}
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 questionAsk a Question
731 491 924 answers to any question