You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hey @lsemerini! Great suggestion. If you want to open a PR for this that would be great. You can do this by adding a check here and returning if apiKey isn't set. This will never load the Segment library, but it won't throw an error.
Another thing is that when you add this check and later try to invoke useSegment() it will throw an error.
I had to do something ugly on my code so it failed silently and to avoid multiple conditionals afterwards.. like this:
const SegmentProviderWrapper: React.FC<SegmentProviderWrapperProps> = ({ children, apiKey }) => {
if (!apiKey) {
console.warn(
'You are using SegmentProvider without an apiKey - Your tracking functions will be mocked by SegmentProviderWrapper',
);
}
return apiKey ? <SegmentProvider apiKey={apiKey}>{children}</SegmentProvider> : children;
};
export const useSegment = () => {
const analytics = useContext(SegmentContext);
if (!analytics) {
// fail silently if segment isnt initialzied properly instead of throw errors
// when implementing a function we should always test that the fallback is available too
return {
initialize: (props: any) => {},
identify: (props: any) => {},
page: (props: any) => {},
track: (props: any) => {}, // etcetera
};
}
return analytics;
};
This way I can still call analytics.track in my code without checking whether is available or not. And I can call analytics = useSegment() even though the provider wasn't added higher up in the tree.
This is a great package - thank you!
One thing I noticed is that if the
apiKey
is undefined, it still builds the CDN url with apiKey undefined.Maybe an enhancement would be to prevent it from working when apiKey isnt passed, so the user doesn't need to validate if the api key is set or not.
The text was updated successfully, but these errors were encountered: