I am trying to filter a set of objects in a state whenever a user clicks a button on my component. The filtering logic works fine, but when it returns to the component, there are no filtered objects, and the property is undefined. Is there a lack of a life cycle method?
Click event:
<div onClick={this.filterMyPosts}>My Posts</div> ... <div> {this.renderPosts()} </div>
filterMyPosts
filterMyPosts() { this.props.updateFilter("myPosts"); // filtering function uses switch statement based on strings to filter posts }
Component Container:
const mapStateToProps = (state) => { return {currentUser: state.session.currentUser, posts: allPostsByFilter(state.posts, state.filter, state.session.currentUser.id, state.bookmarks)} }; const mapDispatchToProps = (dispatch) => ({ updateFilter: (filter) => dispatch(updateFilter(filter)) })
Filtering occurs in another file that returns the filtered events in the object. This logic has no errors.
Problem . By the time the next message function is received, it is undefined. Therefore, somewhere along the way, filtered messages do not return a component.
renderPosts() { return ( <div className ="user-profile-posts"> <ul> {Object.keys(this.props.posts).map(id => <PostIndexItem key={`posts-index-item${id}`} post={this.props.posts[id]} user={true} />)} </ul> </div> ); }
EDIT function - filter
export const allPostsByFilter = (filter, currentUserId, posts) => { switch (filter) { case "myPosts": let postKeys = Object.keys(posts).filter( (id) => { return(posts[id].user_id === currentUserId) }); let userPosts = {} postKeys.forEach( (key) => userPosts[key] = posts[key]) let newPosts = {} let postKeys = Object.keys(posts).filter( (id) => { return (Object.keys(userPosts).includes(id)) }); eventKeys.forEach( (key) => newPosts[key] = posts[key]) return newPosts default: return posts
source share