Question:
I use redux-thunk and I want to receive posts. To receive posts I need to get users. So I have doubts about my thunk, Is it right to get all the data in one thunk, if not how to split it into two thunks?
Thunk example:
export default group_id => {
return async dispatch => {
const users = await API.get(`/users?group_id=${group_id}`) // get users
const posts = await axios.all([...getPosts(users)]) // get all posts by user ids
dispatch(loadUsersAction(users))
dispatch(loadPostsAction(posts))
}
}
There might be several approaches depending of your requirements.
If the purpose is to load, initially users, and then their post, i would call firstly /users
, and then dispatch another action creator to get their /posts
.
Because getting it all together would make your users waiting longer for something to change in the UI (ex: loading spinner), thus i would split these in two separate actions.
export function getUsers(group_id) => {
return async dispatch => {
const users = await API.get(`/users?group_id=${group_id}`);
dispatch(loadUsersAction(users));
return users;
};
};
export function getPostForGroupUsers (group_id) => {
return async dispatch => {
const users = await dispatch(getUsers(group_id));
const posts = await axios.all([...getPosts(users)]);
dispatch(loadPostsAction(posts));
return posts;
}
}
// or just call users, dispatch and get them from store
export function getPostForAllUsers () => {
return async dispatch => {
// this depends on your implementation
const users = getFromReduxStore('users');
const posts = await axios.all([...getPosts(users)]);
dispatch(loadPostsAction(posts));
return posts;
}
}
Maybe you can provide more details of your case, I then could give more precise response.