redux saga - proper return from fetch
Let's say you have the following saga code to call and put a http request.
export function* fetchUser(action) {
try {
const users = yield call(getUsers);
yield put({type: USER_FETCH_SUCCEEDED, users: users });
}
catch (e) {
yield put({type: USER_FETCH_ERROR, message: e.message});
}
}
Here we call getUser which needs to be correctly handle, otherwise you get alots of weird handling issue downstream.
For example, you might return a promise like so,
function getUsers() {
return fetch(FETCH_USER_URL);
}
Or even as follows :-
function getUsers() {
return fetch(FETCH_USER_URL).then(response => response.json())
return fetch(FETCH_USER_URL).then(response => response.json())
}
The proper way is to do as follows Why? Because this will return an array of plain objects instead of Promise(). which you cannot call more than once. Why do you call this more than once? In react lifecycle, your function will get call more than once.
function getUsers() {
return fetch(FETCH_USER_URL).then(response => response.json())
.then(json => json);
.then(json => json);
}
Comments