Usually in my Redux projects I have action and reducer files that come in pairs. So in my actions
folder I will have a posts.js
and in my reducers
folder I will also have a posts.js
. The posts action file usually just dispatch action types that are subscribed to in the posts reducer file.
But now I need to dispatch an action type from the posts
action file that is subscribed to from the authors
reducer file. Is this okay or considered an anti-pattern?
That isn't anti-pattern at all. It's good code-reusability and especially useful for error-handling.
Consider the following example:
import { GET_POSTS } from "./actions/types"
import { setErrors } from "./actions/errors"
import axios from "axios"
export const getPosts = () => {
return (dispatch) => {
axios.get("/api/posts")
.then((res) => {
dispatch({
type: GET_POSTS,
payload: res.data
})
})
.catch((errors) => {
dispatch(setErrors(errors.response.data))
}
}
}
const setErrors = (errors) => {
return {
type: SET_ERRORS,
payload: errors
}
}
So instead of defining a completely new post-related errors action inside posts.js, it makes sense to just import an existing one that is subscribed to your errors-reducer (if any). The same could be said about using your author and post actions together.