I'm trying to implement react-ga but only in production server (I have my local / dev and prod servers).
So, I would like to create a text field in backoffice which value is saved in database.
Then in the front side, I initialize react-ga only if I have a value in database.
To achieve this, I'm trying do this in componentDidUpdate
in App.jsx
.
I retrieve all my data set in backoffice via :
componentDidMount() {
// I get my data in this.props.data_admin
this.props.list_admin();
}
Then in componentDidUpdate(prevProps, prevState)
I check if this.props.data_admin is set and not null, and when I got values I would like to initialize react-ga :
componentDidUpdate(prevProps, prevState, snapshot) {
if (this.props.data_admin) {
// this.props.data_admin.trackingNumber = UA-XXXXXXXXX
ReactGA.initialize(this.props.data_admin.trackingNumber);
}
}
But this gonna be done a lot of times (each time App.jsx is updated). So I should check before initialize if it's already done. How can I check if react-ga is already initialized ?
Thanks for your help
Finally what I did :
I called this.props.list_admin();
in App.jsx constructor and I created a state variable initialized at false :
constructor(props) {
super(props);
this.state = {
googleAnalyticsInitialized: false,
};
this.props.list_admin();
}
Then, in componentDidupdate
I checked values from this.props.data_admin
and if googleAnalyticsInitialized
is false. If it is, I initialiaze Google Analytics with the ID received from the call to the API :
componentDidUpdate(prevProps, prevState, snapshot) {
if (this.props.data_admin && this.props.data_admin.idGoogleAnalytics && !this.state.googleAnalyticsInitialized) {
ReactGA.initialize(this.props.data_admin.idGoogleAnalytics);
this.setState({googleAnalyticsInitialized: true});
}
}
Thanks to @Chukwuemeka Onyenezido who helped me and directed me on the right way.