Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'aws-amplify' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
async init() {
try {
const user = await Auth.currentAuthenticatedUser()
this.username = user.username
this.email = user.signInUserSession.idToken.payload.email
} catch (err) {
console.log('error getting user data... ', err)
}
console.log('username:', this.username)
// check if user exists in db, if not then create user
if (this.username !== '') {
this.checkIfUserExists(this.username)
}
}
return new Promise(async (resolve, reject) => {
Loading.show({
message: "Loading profile..."
});
try {
const {
// @ts-ignore
data: { getLoyalty: loyaltyData }
} = await API.graphql(graphqlOperation(getLoyalty));
const loyalty = new Loyalty(loyaltyData);
commit("SET_LOYALTY", loyalty);
Loading.hide();
resolve();
} catch (err) {
Loading.hide();
reject(err);
}
});
}
componentDidMount() {
// API Gateway
let apiName = 'MyAPIGatewayAPI';
let querypath = '/search/?scan=odcr';
// Loading
this.setState({ isLoading: true });
// Scan DynamoDB for results
API.get(apiName, querypath).then(response => {
this.setState({
instances: response,
isLoading: false
});
})
.then(response => {
console.log(this.state.instances)
})
.catch(error => {
this.setState({ error, isLoading: false })
console.log(error.response)
});
}
render() {
import Amplify, { Auth } from 'aws-amplify';
import { GraphQLClient } from 'graphql-request';
import { LOCAL_STORAGE_KEY, GET_USER_QUERY } from './const';
import { client } from '../apollo';
console.log('CLIENT', client);
Amplify.configure({
Auth: {
// identityPoolId: 'us-west-2:0de73b6e-0624-4f46-9e56-14e51ecf282a',
region: 'us-west-2',
userPoolId: 'us-west-2_uzyDC8Snl',
userPoolWebClientId: '181177ggq1ot45s6t791vposkr',
// cookieStorage: {
// domain: '.law.haus',
// path: '/',
// expires: 365,
// secure: true,
// },
},
});
const isBrowser = typeof window !== `undefined`;
return function(dispatch) {
console.log('actions.validateUserSession()');
Auth.currentAuthenticatedUser()
.then(currentAuthUser => {
console.log('actions.validateUserSession():Auth.currentAuthenticatedUser() currentAuthUser:', currentAuthUser);
// grab the user session
Auth.userSession(currentAuthUser)
.then(session => {
console.log('actions.validateUserSession():Auth.userSession() session:', session);
// finally invoke isValid() method on session to check if auth tokens are valid
// if tokens have expired, lets call "logout"
// otherwise, dispatch AUTH_USER success action and by-pass login screen
if (session.isValid()) {
// fire user is authenticated
dispatch({ type: AUTH_USER });
//history.push('/');
} else {
// fire user is unauthenticated
dispatch({ type: UNAUTH_USER });
stories.forEach(({ key }) => {
Storage.get(key, {
bucket: "data.interviewjs.io",
level: "private"
})
.then((url) => {
axios
.get(url)
.then((response) => {
// console.log('AWS', response.data);
if (response.data.ignore) {
dispatch(noop());
} else {
dispatch(syncStory(response.data));
}
})
.catch((error) => Raven.captureException(error));
})
async created() {
if (this.$store.getters.isAuth == true) {
// If created with valid authentication, read in user assets,
// read initial dispenser status then sub to MQTT topics
let response;
let authInfo;
let mqttResponse;
authInfo = await Auth.currentUserInfo();
response = await API.post("CDD_API", "/getResources", {
body: { cognitoIdentityId: authInfo.id }
});
console.log("resources response is ", response)
// Get resources needed to complete setup
await this.$store.dispatch("setAssets", response);
// Read dispenser shadow and credit status, and set
response = await API.get("CDD_API", "/status");
this.$store.dispatch("setStatus", response);
this.sub1
.subscribe([
"".concat("events/", this.$store.getters.dispenserId),
"".concat("$aws/things/", this.$store.getters.dispenserId, "/shadow/update/accepted")
])
.subscribe({
next: async () => {
// Use the event to trigger a getResources call
const currentUser = async () => {
try {
// check if user is authenticated
// try will throw if not
const user = await Auth.currentAuthenticatedUser();
// attributes are only updated here until re-auth
// so grab attributes from here
const attributes = await Auth.currentUserInfo();
const realuser = { ...user, ...{ attributes: attributes.attributes } };
setCurrentUser(realuser);
// attach sdk
// console.log("in load: realuser", realuser);
const sdkEnv = getSdkEnvironment(
SdkEnvironmentNames[`${config.SDK_ENV}`],
);
// check or set up local storage and initialize sdk connection
const sdk = new createSdk(
sdkEnv.setConfig('storageAdapter', localStorage),
);
await sdk.initialize();
// check if account is connected in local storage
.then(user => {
this.isLoading = false;
Auth.currentUserInfo()
.then(info => {
const payload = { username: user.username, jwt: user.signInUserSession.idToken.jwtToken };
this.$store.dispatch("setLoggedIn", payload );
this.statusMessage = "Loading user details";
console.log("current user info ", info);
console.log("initial JWT", user.signInUserSession.idToken.jwtToken)
if (!this.redirectTo) {
// No called route, send to root (/)
this.$router.push({
path: "/",
});
} else {
// When authenticated, forward to auth required route
this.$router.push({
path: this.redirectTo
pageHtml = getPageHtml(newComponents)
const slug = slugify(pageTitle)
const input = {
name: pageTitle,
slug,
content: pageHtml,
components: JSON.stringify(newComponents),
published: publishingState === 'publish' ? true : false
}
if (pageId) {
operation = updatePage
input['id'] = pageId
}
const newPageData = await API.graphql(graphqlOperation(operation, { input }))
const { createPage } = newPageData.data
baseComponents = JSON.parse(baseComponents)
// worst hack ever. couldn't figure another way, so for now doing this:
// stringifying state, then parsing and updating because state was being mutated somehow.
baseComponents = baseComponents.map((c, i) => {
c.component = newComponents[i].component
if (c.type === 'image') {
c.content = {
...c.content,
src: newComponents[i].content.src
}
} else {
c.content = newComponents[i].content
}