I'm trying to understand async actions in redux. Reading this page I got the following example:
export function fetchPosts(subreddit) {
return (dispatch) => {
dispatch(requestPosts(subreddit))
return fetch(`https://www.reddit.com/r/${subreddit}.json`)
.then(
response => response.json(),
// Do not use catch, because that will also catch
// any errors in the dispatch and resulting render,
// causing a loop of 'Unexpected batch number' errors.
// https://github.com/facebook/react/issues/6895
error => console.log('An error occurred.', error)
)
.then(json =>
dispatch(receivePosts(subreddit, json))
)
}
}
About that comment, it is a common error to swallow react exceptions, what I'm trying to avoid... I'm trying to use the new javascript async/await syntax here... how the equivalent code with the exactly same behavior would be?
I thought about this first:
export function fetchPosts(subreddit) {
return async (dispatch) => {
dispatch(requestPosts(subreddit));
try {
const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
const json = await response.json();
dispatch(receivePosts(subreddit, json));
}
catch (error) {
console.log('An error occurred.', error);
}
}
}
But I had the feeling that this is exactly what that comment tells to avoid. Then I thought about this code:
export function fetchPosts(subreddit) {
return async (dispatch) => {
dispatch(requestPosts(subreddit));
try {
const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
const json = await response.json();
}
catch (error) {
console.log('An error occurred.', error);
return;
}
dispatch(receivePosts(subreddit, json));
}
}
But in the case of an error, I'm not sure if the behavior is the same as the example without async/await. I'm not sure if I need to put that return
inside the catch
block. And the example returns a promise, I'm not sure if it still happens with my code.
Searching about it, I only found this question but without response, and I found a redux-saga component that uses generators/yield syntax. Should I use redux-saga instead of redux-thunk with async/await?