rsnext/examples/with-firebase-authentication/utils/pageWrappers/withAuthUserInfo.js

56 lines
1.6 KiB
JavaScript
Raw Normal View History

/* eslint react/jsx-props-no-spreading: 0 */
import React from 'react'
import PropTypes from 'prop-types'
import { get } from 'lodash/object'
import { AuthUserInfoContext } from '../auth/hooks'
// Provides an AuthUserInfo prop to the composed component.
export default function withAuthUserInfo(ComposedComponent) {
2020-05-18 21:24:37 +02:00
const WithAuthUserInfoComp = (props) => {
const { AuthUserInfo: AuthUserInfoFromSession, ...otherProps } = props
return (
<AuthUserInfoContext.Consumer>
2020-05-18 21:24:37 +02:00
{(AuthUserInfo) => (
<ComposedComponent
{...otherProps}
AuthUserInfo={AuthUserInfo || AuthUserInfoFromSession}
/>
)}
</AuthUserInfoContext.Consumer>
)
}
2020-05-18 21:24:37 +02:00
WithAuthUserInfoComp.getInitialProps = async (ctx) => {
const AuthUserInfo = get(ctx, 'myCustomData.AuthUserInfo', null)
// Evaluate the composed component's getInitialProps().
let composedInitialProps = {}
if (ComposedComponent.getInitialProps) {
composedInitialProps = await ComposedComponent.getInitialProps(ctx)
}
return {
...composedInitialProps,
AuthUserInfo,
}
}
WithAuthUserInfoComp.displayName = `WithAuthUserInfo(${ComposedComponent.displayName})`
WithAuthUserInfoComp.propTypes = {
AuthUserInfo: PropTypes.shape({
AuthUser: PropTypes.shape({
id: PropTypes.string.isRequired,
email: PropTypes.string.isRequired,
emailVerified: PropTypes.bool.isRequired,
}),
token: PropTypes.string,
}),
}
WithAuthUserInfoComp.defaultProps = {}
return WithAuthUserInfoComp
}