Reputation: 390
I have component where I show My User Profile Page. Inside this component I have a button. When clicked, this button uses an action function to show another component with my followers.
Inside the component with my followers list, I can click on each follower and open his profile with the user profile component and show this follower's info and his profile. Everything works correctly, until I click back. Then I see a list of followers that doesn't belong to me, but belongs to the profile I just clicked back from.
Because the reducers are rewriting the state to whoever I'm currently viewing, if I go to other users' followers page and click to another people, I see the same behavior. I think I need to save the previous user's follower list and previous profile, or maybe something like copy the previous state in the reducer, but I don't know how.
I'm using Wilddog for my backend, which is similar to Firebase but for China. I've attached all my files to the GIST linked below.
It seems like the solution should be obvious, but I am not getting the trick to solve it.
https://gist.github.com/myfailemtions/0c4b79fef1aa5e6d67d3f828717474f5
Upvotes: 1
Views: 663
Reputation: 6375
It looks to me like the code with the problem might be the following:
class Followers extends Component {
componentWillMount() {
const {uid} = this.props.user;
this.props.followersFetch({uid});
this.createDataSource(this.props)
}
componentWillReceiveProps(nextProps) {
this.createDataSource(nextProps)
}
// ..omitted
}
It looks like you're fetching an updated list when the component mounts, but forgetting to when the props are updated. Adding this.props.followersFetch(nextProps({this.props.user.uid});
to your componentWillReceiveProps
will probably fix the bug.
If you're worried about making multiple calls to the server, you're going to need to implement caching in your reducer. Right now your code snippet show that you're overwriting your entire state (?!) with your follower fetch - which is probably not what you want. If you're looking to just rollback to a previous state, storing your state with a library like Immutable.js might be what you're looking for.
EDIT
An quick and dirty modification to your existing action to store previous states. Doing it this way will require refactoring most of your views, because it no longer deletes all state managed by the reducer whenever you fetch your followers.
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case FOLLOWING_FETCH:
//Following lines updates state, rather than rewrites it
return {
...state,
cachedFollowers: state.cachedFollowers.push(action.payload)
};
default:
return state
}
};
Warning: the above code is untested
Upvotes: 1