EDIT 9/5/17:
It turns out I had an issue with a different part of my react code in React that led me to believe that my stack was not properly resetting. One of the few components I was rendering on the /Profile page was calling array.length on an empty array, and that error was preventing my code from running and my browsers was freezing. Thanks for looking regardless
I am attempting to reset the state of an object (let's call it UID) in my store when a component unmounts.
The initial state of UID is an empty string, when a user clicks on a username (a user that's made a post) I am rendering a profile component, but before the profile component is rendered, I am populating the UID, and rendering a profile component that matches the UID.
What I'd like to do now is clear the UID when the Profile component unmounts, so if a user clicks on a different user name, I can render a different profile.
Profile component:
class Profile extends Component {
componentWillUnmount() {
this.props.clearUserUid()
}
render() {
return (
<Grid id="profile">
<Grid.Row>
<Grid.Column className='profileheader'>
<ProfileHeader />
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<AddSocial/>
<ListOfSocialLinks/>
</Grid.Column>
</Grid.Row>
</Grid>
);
}
}
Action
export const clearUserUid = uid => ({
type: 'CLEAR_UID', payload: ''
})
Reducer:
import initialState from './initialState';
export default function (userUid = initialState.userUid, action) {
switch (action.type) {
case 'CLEAR_UID':
return action.payload;
default:
return userUid;
}
}
Initial State
userUid: '',
component listening to userUid
class ListOfSocialLinks extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
if(this.props.userUid && this.props.userUid.length > 0) {
firebase.database().ref(`users/${this.props.userUid}/social`).on('value', snapshot => this.props.fetchSocial(snapshot.val()));
}
else {
firebase.database().ref(`users/${this.props.userData.uid}`).on('value', snapshot => {
return this.props.fetchSocial(snapshot.val())
})
}
}
render() {
const { social, userData } = this.props;
return (<div className="social"> { this.renderSocial(social, userData) }</div>);
}
}
userData.uid is always available for the user to view their own profile.
clearUserUid action runs, and the state of my store changes to an empty string, but, when I click on a different user after the profile component unmounts, I get an error on the page.
How can I properly reset the state of the store to an empty string?
It looks like your missing some code in your example but my guess is that the component itself is actually not unmounting. When properties change through redux, it doesn't mount/unmount, it just re-renders.
There are a few events that you can bolt into. My suggestion is to use componentWillUpdate to see that the paramater uid has changed and to trigger the clear.
If this is not the case, you may need to re-work the question with more of an example.