I'd been working with React & Redux for some time when a work colleague saw some code I wrote and commented on it.
SomeComponent.js
class SomeComponent extends Component {
async componentDidMount() {
await this.props.fetchPosts();
if (this.props.posts.length < 1)
return navigateTo( /* someOtherPlace */);
}
render() {
return (
<>
{this.props.posts.map(
(postData, i) => <Post key={i} {...postData}/>
)}
</>
);
}
}
const mapStateToProps = ({ posts }) => ({
posts: posts.list,
isFetching: posts.isFetching
});
export default connect(mapStateToProps, { fetchPosts })(SomeComponent);
actions/posts.js
export const fetchPosts = () => async dispatch => {
dispatch(requestPosts());
let posts;
try {
posts = (await api.get('/posts')).data
} catch (e) {
posts = e;
}
dispatch(receivePosts(posts));
}
He basically said that I shouldn't be awaiting for fetchPosts()
action, instead I should just call it, and let it update props, re-render and perform the conditional navigation in componentDidUpdate
which when he said it, it totally made sense to me.
But now I keep asking myself if what I was doing was really that bad, potencially buggy or just a bad practice that added more complexity.
He didn't mention the reasons why it was wrong other than it wasn't the React way of doing it.
EDIT: Added code snippet showing that the approach actually does work and doesn't perform faulty reads.