Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: migrate useAuth hook for v6 #1137

Merged
merged 2 commits into from
Nov 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -879,6 +879,61 @@ export default function Test(props: TestProps): React.ReactElement {
"
`;

exports[`amplify render tests bindings auth supports auth bindings in actions - amplify js v6 1`] = `
"/* eslint-disable */
import * as React from \\"react\\";
import { getOverrideProps, useAuth, useDataStoreCreateAction } from \\"./utils\\";
letsbelopez marked this conversation as resolved.
Show resolved Hide resolved
import { Customer } from \\"../models\\";
import { schema } from \\"../models/schema\\";
import { Button, ButtonProps } from \\"@aws-amplify/ui-react\\";

export type EscapeHatchProps = {
[elementHierarchy: string]: Record<string, unknown>;
} | null;

export type VariantValues = { [key: string]: string };
export type Variant = {
variantValues: VariantValues;
overrides: EscapeHatchProps;
};
export declare type PrimitiveOverrideProps<T> = Partial<T> &
React.DOMAttributes<HTMLDivElement>;
export declare type ComponentWithAuthEventBindingOverridesProps = {
ComponentWithAuthEventBinding?: PrimitiveOverrideProps<ButtonProps>;
} & EscapeHatchProps;
export type ComponentWithAuthEventBindingProps = React.PropsWithChildren<
Partial<ButtonProps> & {
overrides?: ComponentWithAuthEventBindingOverridesProps | undefined | null;
}
>;
export default function ComponentWithAuthEventBinding(
props: ComponentWithAuthEventBindingProps
): React.ReactElement {
const { overrides, ...rest } = props;
const authAttributes = useAuth().user?.attributes ?? {};
letsbelopez marked this conversation as resolved.
Show resolved Hide resolved
const componentWithAuthEventBindingOnClick = useDataStoreCreateAction({
model: Customer,
fields: {
userName: authAttributes[\\"username\\"],
favoriteIceCream: authAttributes[\\"custom:favorite_icecream\\"],
},
schema: schema,
});
return (
/* @ts-ignore: TS2322 */
<Button
children=\\"Create\\"
onClick={() => {
componentWithAuthEventBindingOnClick();
}}
{...getOverrideProps(overrides, \\"ComponentWithAuthEventBinding\\")}
{...rest}
></Button>
);
}
"
`;

exports[`amplify render tests bindings auth supports auth bindings in actions 1`] = `
"/* eslint-disable */
import * as React from \\"react\\";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,13 @@ describe('amplify render tests', () => {
generateWithAmplifyRenderer('bindings/auth/componentWithAuthActionBinding').componentText,
).toMatchSnapshot();
});
it('supports auth bindings in actions - amplify js v6', () => {
expect(
generateWithAmplifyRenderer('bindings/auth/componentWithAuthActionBinding', {
dependencies: { 'aws-amplify': '^6.0.0' },
}).componentText,
).toMatchSnapshot();
});
});

describe('data', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -808,7 +808,7 @@ export const processFile = async ({ file }) => {
exports[`render utils file render all utils - amplify v6 1`] = `
"/* eslint-disable */
import * as React from \\"react\\";
import { signOut } from \\"aws-amplify/auth\\";
import { fetchUserAttributes, signOut } from \\"aws-amplify/auth\\";
import { DataStore } from \\"aws-amplify/datastore\\";
import { Hub } from \\"aws-amplify/utils\\";
export const UI_CHANNEL = \\"ui\\";
Expand Down Expand Up @@ -1305,6 +1305,60 @@ export const useAuthSignOutAction = (options) => async () => {
);
}
};
export const useAuth = () => {
const [result, setResult] = React.useState({
error: undefined,
isLoading: true,
user: undefined,
});
const fetchCurrentUserAttributes = React.useCallback(async () => {
setResult((prevResult) => ({ ...prevResult, isLoading: true }));
try {
const attributes = await fetchUserAttributes();
setResult({ user: { attributes }, isLoading: false });
} catch (error) {
setResult({ error, isLoading: false });
}
}, []);
const handleAuth = React.useCallback(
({ payload }) => {
switch (payload.event) {
case \\"signedIn\\":
case \\"signUp\\":
case \\"tokenRefresh\\":
case \\"autoSignIn\\": {
fetchCurrentUserAttributes();
break;
}
case \\"signedOut\\": {
setResult({ user: undefined, isLoading: false });
break;
}
case \\"tokenRefresh_failure\\":
case \\"signIn_failure\\": {
setResult({ error: payload.data, isLoading: false });
break;
}
case \\"autoSignIn_failure\\": {
setResult({ error: new Error(payload.message), isLoading: false });
break;
}
default: {
break;
}
}
},
[fetchCurrentUserAttributes]
);
React.useEffect(() => {
const unsubscribe = Hub.listen(\\"auth\\", handleAuth, \\"useAuth\\");
fetchCurrentUserAttributes();
return unsubscribe;
}, [handleAuth, fetchCurrentUserAttributes]);
return {
...result,
};
};
export const validateField = (value, validations) => {
for (const validation of validations) {
if (value === undefined || value === \\"\\" || value === null) {
Expand Down
2 changes: 2 additions & 0 deletions packages/codegen-ui-react/lib/imports/import-mapping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export enum ImportValue {
USE_AUTH = 'useAuth',
AUTH = 'Auth',
SIGN_OUT = 'signOut',
FETCH_USER_ATTRIBUTES = 'fetchUserAttributes',
GET_OVERRIDES_FROM_VARIANTS = 'getOverridesFromVariants',
USE_BREAKPOINT_VALUE = 'useBreakpointValue',
VARIANT = 'Variant',
Expand Down Expand Up @@ -98,4 +99,5 @@ export const ImportMapping: Record<ImportValue, ImportSource> = {
[ImportValue.PROCESS_FILE]: ImportSource.UTILS,
[ImportValue.USE_EFFECT]: ImportSource.REACT,
[ImportValue.USE_STATE]: ImportSource.REACT,
[ImportValue.FETCH_USER_ATTRIBUTES]: ImportSource.AMPLIFY_AUTH,
};
Original file line number Diff line number Diff line change
Expand Up @@ -777,7 +777,12 @@ export abstract class ReactStudioTemplateRenderer extends StudioTemplateRenderer

const authStatement = this.buildUseAuthenticatedUserStatement();
if (authStatement !== undefined) {
this.importCollection.addMappedImport(ImportValue.USE_AUTH);
if (getAmplifyJSVersionToRender(this.renderConfig.dependencies) === AMPLIFY_JS_V5) {
this.importCollection.addMappedImport(ImportValue.USE_AUTH);
} else {
// V6 useAuth is in the utils file
this.importCollection.addImport(ImportSource.UTILS, ImportValue.USE_AUTH);
}
statements.push(authStatement);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import {
createDataStorePredicateString,
useDataStoreBindingString,
useAuthSignOutActionStringV6,
useAuthString,
} from './utils-file-functions';
import { getAmplifyJSVersionToRender } from './helpers/amplify-js-versioning';
import { AMPLIFY_JS_V6 } from './utils/constants';
Expand Down Expand Up @@ -101,9 +102,11 @@ export class ReactUtilsStudioTemplateRenderer extends StudioTemplateRenderer<

if (getAmplifyJSVersionToRender(this.renderConfig.dependencies) === AMPLIFY_JS_V6) {
this.importCollection.addImport(ImportSource.AMPLIFY_AUTH, ImportValue.SIGN_OUT);
this.importCollection.addImport(ImportSource.AMPLIFY_AUTH, ImportValue.FETCH_USER_ATTRIBUTES);
this.importCollection.addImport(ImportSource.AMPLIFY_DATASTORE_V6, ImportValue.DATASTORE);
this.importCollection.addImport(ImportSource.AMPLIFY_UTILS, ImportValue.HUB);
parsedUtils.push(useAuthSignOutActionStringV6);
parsedUtils.push(useAuthString);
} else {
this.importCollection.addMappedImport(ImportValue.HUB, ImportValue.DATASTORE, ImportValue.AUTH);
parsedUtils.push(useAuthSignOutActionString);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export * from './useTypeCastFields';
export * from './useDataStoreCreateAction';
export * from './useDataStoreUpdateAction';
export * from './useDataStoreDeleteAction';
export * from './useAuth';
export * from './createDataStorePredicate';
export * from './useDataStoreBinding';
export * from './constants';
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
export const useAuthString = `export const useAuth = () => {
const [result, setResult] = React.useState({
error: undefined,
isLoading: true,
user: undefined,
});

const fetchCurrentUserAttributes = React.useCallback(async () => {
setResult((prevResult) => ({ ...prevResult, isLoading: true }));

try {
const attributes = await fetchUserAttributes();
setResult({ user: {attributes}, isLoading: false });
} catch (error) {
setResult({ error, isLoading: false });
}
}, []);

const handleAuth = React.useCallback(
({ payload }) => {
switch (payload.event) {
case 'signedIn':
case 'signUp':
case 'tokenRefresh':
case 'autoSignIn': {
fetchCurrentUserAttributes();
break;
}
case 'signedOut': {
setResult({ user: undefined, isLoading: false });
break;
}

case 'tokenRefresh_failure':
case 'signIn_failure': {
setResult({ error: payload.data, isLoading: false });
break;
}
case 'autoSignIn_failure': {
setResult({ error: new Error(payload.message), isLoading: false });
break;
}

default: {
break;
}
}
},
[fetchCurrentUserAttributes]
);

React.useEffect(() => {
const unsubscribe = Hub.listen('auth', handleAuth, 'useAuth');
fetchCurrentUserAttributes();

return unsubscribe;
}, [handleAuth, fetchCurrentUserAttributes]);

return {
...result,
};
};`;
Loading