Reputation: 683
Able to render props in my Dashboard component, unable to pass this to componentDidMount for further ajax processing.
Render is working fine and display information.
I am using firebase and that's working correctly.
App.js
// React core.
import React, { Component } from 'react';
import Dashboard from './components/Dashboard';
class App extends Component {
//firebase...
state = {
isSignedIn: undefined,
displayName: undefined,
email: undefined
};
componentDidMount() {
this.setState({providerData: user.providerData})
this.setState({ displayName: user.providerData[0].displayName })
this.setState({ email: user.providerData[0].email })
});
}
render() {
return (
<div className={styles.container}>
{this.state.isSignedIn !== undefined && !this.state.isSignedIn &&
//Not signed-in yet
<div>
<Login />
</div>
}
{this.state.isSignedIn &&
//Signed in
<div>
<Dashboard
displayName={this.state.displayName}
email={this.state.email} />
</div>
}
</div>
);
}
}
export default App;
Dashboard.js
import React, { Component } from 'react';
class Dashboard extends Component {
componentDidMount() {
var thisComponent = this
console.log(thisComponent.props.email)
}
render() {
const email = this.props.email
return (
<div>
<h1>Hello, {this.props.displayName}!</h1>
<h2>Your email is: {email}</h2>
</div>
);
}
}
export default Dashboard;
The componentDidMount in Dashboard.js is what is tripping me up. Unable to send email value for further ajax process. Should be getting the email in console, instead, I'm getting "undefined".
Upvotes: 2
Views: 2772
Reputation: 31605
The only case where what is happening to you can happen is if email
is comming from some asyncronous call. This is how it's happening:
email
is an undefined
state. But you make a asyncronous call to get email
.email
is undefined
because the asyncronous call isn't finished yet, so you console undefined
in componentDidMount
.Dashboard
with the correct email.This way, you see email rendered but in componentDidMount
it's undefined. It's rendering 2 times and only in the seconds time, after the component already mount, you are getting the correct email
.
This is the only case where you can see the data, but it's undefined in componentDidMount
and I'm almost sure that this is your case.
You provided almost no code to solve your problem, and the only thing I can do is give you the reason of your problem by doing some assumptions of your case. Hope this helps you understand your problem and solve it.
Edit: In your code, you are getting the email using firebase ( asyncronous call), so my assumptions are correct, now just need to know what is the expected results.
Edit: If you need to do some action with email inside the component, use componentDidMount
For your case you can do
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.email != undefined && this.props.email !== prevProps.email) {
// Do what you want with email
}
}
Upvotes: 3