Skip to content

Commit

Permalink
refactor: Move set user to componentDidMount
Browse files Browse the repository at this point in the history
  • Loading branch information
mikechu-optimizely committed Dec 28, 2023
1 parent 9ed3464 commit e8e75cd
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions src/Provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,14 @@ interface OptimizelyProviderState {
export class OptimizelyProvider extends React.Component<OptimizelyProviderProps, OptimizelyProviderState> {
constructor(props: OptimizelyProviderProps) {
super(props);
const { optimizely, userId, userAttributes, user } = props;
}

async componentDidMount() {
const { optimizely, userId, userAttributes, user } = this.props;

if (!optimizely) {
logger.error('OptimizelyProvider must be passed an instance of the Optimizely SDK client');
return;
}

let finalUser: UserInfo | null = null;
Expand All @@ -70,17 +74,28 @@ export class OptimizelyProvider extends React.Component<OptimizelyProviderProps,
// deprecation warning
logger.warn('Passing userId and userAttributes as props is deprecated, please switch to using `user` prop');
} else {
finalUser = {
id: optimizely.getVuid() || null,
attributes: {},
};
const localStorageVuid = localStorage.getItem('optimizely-vuid');

if (localStorageVuid) {
finalUser = {
id: localStorageVuid,
attributes: {},
};
} else {
await optimizely.onReady();

finalUser = {
id: optimizely.getVuid() || null,
attributes: {},
};
}
}

if (finalUser) {
try {
optimizely.setUser(finalUser);
} catch {
logger.error('Unable to set user because passed in optimizely object does not contain the setUser function.');
logger.error('Unable to set user. Prop optimizely object does not contain the setUser function.');
}
}
}
Expand Down

0 comments on commit e8e75cd

Please sign in to comment.