Reputation: 315
Say my homepage renders a feed of all posts when no user is signed in, else renders a feed of posts relevant to signed in user. With Flux I would simply have a function
getNewFeedPosts(){
this.setState({posts: []});
ajaxFetchPostsFromServer();
}
And add it as a listener to my session store. I would also have a function listening to my post store that would set the state to the new posts once they came back in response to ajaxFetchPostsFromServer being called.
What is the best practice way to do this in Redux with connectors and a provider?
Currently I have a feed container:
const mapStateToProps = (state) => ({
tweets: state.tweets,
});
const mapDispatchToProps = (dispatch) => ({
getTweets: (currUserId) => {
return dispatch(fetchAllTweets(currUserId));
}
});
const FeedContainer = connect(mapStateToProps, mapDispatchToProps)(Feed);
A feed:
class Feed extends React.Component {
constructor(props) {
super(props);
}
componentWillMount(){
this.props.getTweets();
}
render(){
const tweets = this.props.tweets;
const originalTweetIds = Object.keys(tweets);
return (
<div>
<ul>
{ originalTweetIds.map((originalTweetId) => {
return (
<li key={originalTweetId}>
{post info goes here}
</li>);
})}
</ul>
</div>
)
}
};
1) Right now I'm calling getTweets when Feed's about to mount, but if I change my session status in the other component the feed doesn't change, I suppose because it is not remounting, so how should I be doing this to make it change.
2) Also in actuality in getTweets, before I make the ajax request I want to set tweets in my store to [] to prevent tweets from the previous page (say before I logged in) from remaining on the page until the response with the proper tweets comes back. What is best practice to accomplish this?
All input is greatly appreciated :)
Upvotes: 0
Views: 30
Reputation: 4097
1) Right now I'm calling getTweets when Feed's about to mount, but if I change my session status in the other component the feed doesn't change, I suppose because it is not remounting, so how should I be doing this to make it change.
You need to call dispatch(fetchAllTweets(currUserId))
from the other component when you "change the session status". It will update your Feed
component as soon as state.tweets
is updated.
2) Also in actuality in getTweets, before I make the ajax request I want to set tweets in my store to [] to prevent tweets from the previous page (say before I logged in) from remaining on the page until the response with the proper tweets comes back. What is best practice to accomplish this?
You can change your mapDispatchToProps
to:
const mapDispatchToProps = (dispatch) => ({
getTweets: (currUserId) => {
dispatch(clearTweets());
return dispatch(fetchAllTweets(currUserId));
}
});
Create an action creator:
const clearTweets = () => ({ type: 'CLEAR_TWEETS' });
And in the reducer that updates the tweets
state you can do something like this:
switch (action.type) {
case 'CLEAR_TWEETS':
return [];
// other actions
}
Upvotes: 1