Reputation: 519
I am working on a blog post project. I have a method renderPostList() that renders a list of posts. I am using the .map function on the array. When I access /post/list route, the Axios request is not firing and there is nothing in the redux store. Therefore, undefined.map() is called that causes this error. The console.log(this.props.posts) is returning an empty array due to request failure. Even if I write a conditional of "if(this.props.posts)" the method still executes the .map on the undefined array. Is there a way to make this work correctly? I need the data to be passed before .map executes. And why the conditional is not working?
componentDidMount() {
this.props.getPosts();
this.setState({
items: this.props.posts.filter(function (post) {
return post.isRelated === false;
}).length,
});
}
renderPostList() {
if (this.props.posts) { //not working conditional
console.log(this.props.posts);
let filtered_posts = this.props.posts.filter(function (post) {
return post.isRelated === false;
});
var postChunks = this.chunkArray(filtered_posts, 3);
return postChunks[this.state.activePage - 1].map(
({ title, meta_info, timestamp, img, id }) => {
return (
<div className="item" key={id}>
<Post
title={title}
meta_info={meta_info}
timestamp={timestamp}
img={img}
/>
</div>
);
}
);
}
return null;
}
const mapStateToProps = (state) => {
return { posts: state.posts };
};
export default connect(mapStateToProps, { getPosts })(News);
Action
export const getPosts = () => async (dispatch) => {
const response = await api.get("post/list");
dispatch({ type: "GET_POSTS", payload: response.data });
};
Reducer
export default (state = [], action) => {
switch (action.type) {
case 'GET_POSTS':
return action.payload;
default:
return state;
}
};
Axios instance
export default axios.create({
baseURL: dev_url,
headers: {
"X-Requested-With": "XMLHttpRequest",
},
});
I will appreciate any feedback on this code. Thanks!
Upvotes: 0
Views: 156
Reputation: 618
The condition will pass cause javascript script returns true for an empty array. the condition should be
if(this.props.post.length)
if the array length is zero the condition will not pass.
Upvotes: 1