aws-amplify / amplify-js

A declarative JavaScript library for application development using cloud services.
https://docs.amplify.aws/lib/q/platform/js
Apache License 2.0
9.4k stars 2.11k forks source link

Unable to access database user from my local server in the remote server: LOG {"ACTIVITY_NULL": 4, "PERMISSION_DENIED": 1, "POSITION_UNAVAILABLE": 2, "TIMEOUT": 3, "code": 3, "message": "Location request timed out"} #13118

Open elkee2003 opened 4 months ago

elkee2003 commented 4 months ago

Before opening, please confirm:

JavaScript Framework

React Native

Amplify APIs

Authentication, GraphQL API, DataStore, Storage

Amplify Version

v6

Amplify Categories

auth, storage, api

Backend

Amplify CLI

Environment information

``` # Put output below this line ystem: OS: Windows 11 10.0.22000 CPU: (4) x64 Intel(R) Core(TM) i5-6200U CPU @ 2.30GHz Memory: 1.59 GB / 7.88 GB Binaries: Node: 20.11.0 - C:\Program Files\nodejs\node.EXE npm: 9.8.1 - C:\Program Files\nodejs\npm.CMD Browsers: Edge: Spartan (44.22000.120.0), Chromium (122.0.2365.80) Internet Explorer: 11.0.22000.120 npmPackages: @aws-amplify/react-native: ^1.0.17 => 1.0.17 @aws-amplify/rtn-web-browser: ^1.0.16 => 1.0.16 @aws-amplify/ui-react-native: ^2.1.2 => 2.1.2 @babel/core: ^7.20.0 => 7.23.9 @babel/preset-env: ^7.20.0 => 7.23.9 @babel/runtime: ^7.20.0 => 7.23.9 @react-native-async-storage/async-storage: ^1.22.0 => 1.22.0 @react-native-community/geolocation: ^3.1.0 => 3.1.0 @react-native-community/netinfo: ^11.3.0 => 11.3.0 @react-native-masked-view/masked-view: ^0.3.1 => 0.3.1 @react-native/babel-preset: 0.73.21 => 0.73.21 @react-native/eslint-config: 0.73.2 => 0.73.2 @react-native/metro-config: 0.73.5 => 0.73.5 @react-native/typescript-config: 0.73.1 => 0.73.1 @react-navigation/drawer: ^6.6.7 => 6.6.7 @react-navigation/native: ^6.1.10 => 6.1.10 @react-navigation/stack: ^6.3.21 => 6.3.21 @types/react: ^18.2.6 => 18.2.55 @types/react-test-renderer: ^18.0.0 => 18.0.7 HelloWorld: 0.0.1 aws-amplify: ^6.0.17 => 6.0.17 aws-amplify/adapter-core: undefined () aws-amplify/analytics: undefined () aws-amplify/analytics/kinesis: undefined () aws-amplify/analytics/kinesis-firehose: undefined () aws-amplify/analytics/personalize: undefined () aws-amplify/analytics/pinpoint: undefined () aws-amplify/api: undefined () aws-amplify/api/server: undefined () aws-amplify/auth: undefined () aws-amplify/auth/cognito: undefined () aws-amplify/auth/cognito/server: undefined () aws-amplify/auth/enable-oauth-listener: undefined () aws-amplify/auth/server: undefined () aws-amplify/datastore: undefined () aws-amplify/in-app-messaging: undefined () aws-amplify/in-app-messaging/pinpoint: undefined () aws-amplify/push-notifications: undefined () aws-amplify/push-notifications/pinpoint: undefined () aws-amplify/storage: undefined () aws-amplify/storage/s3: undefined () aws-amplify/storage/s3/server: undefined () aws-amplify/storage/server: undefined () aws-amplify/utils: undefined () babel-jest: ^29.6.3 => 29.7.0 eslint: ^8.19.0 => 8.56.0 geolocationexample: 0.0.0 jest: ^29.6.3 => 29.7.0 prettier: 2.8.8 => 2.8.8 react: 18.2.0 => 18.2.0 react-native: 0.73.4 => 0.73.4 react-native-gesture-handler: ^2.15.0 => 2.15.0 react-native-get-random-values: ^1.10.0 => 1.10.0 react-native-google-places-autocomplete: ^2.5.6 => 2.5.6 react-native-maps: ^1.10.2 => 1.10.2 react-native-maps-directions: ^1.9.0 => 1.9.0 react-native-permissions: ^4.1.1 => 4.1.1 react-native-reanimated: ^3.7.0 => 3.7.0 react-native-safe-area-context: ^4.9.0 => 4.9.0 react-native-screens: ^3.29.0 => 3.29.0 react-native-url-polyfill: ^2.0.0 => 2.0.0 react-native-vector-icons: ^10.0.3 => 10.0.3 react-test-renderer: 18.2.0 => 18.2.0 typescript: 5.0.4 => 5.0.4 npmGlobalPackages: @aws-amplify/cli: 12.10.1 npm: 9.8.1 npm notice npm notice New major version of npm available! 9.8.1 -> 10.5.0 npm notice Changelog: https://github.com/npm/cli/releases/tag/v10.5.0 npm notice Run npm install -g npm@10.5.0 to update! npm notice ```

Describe the bug

When I create a user, I am unable to see the user, in other words, when the app loads it does not access the user, even when I console.log:

import { createContext, useState,useEffect, useContext } from "react";
import { confirmResetPassword, getCurrentUser } from 'aws-amplify/auth';
import { DataStore, Predicates } from 'aws-amplify/datastore';
import { User } from "../models";
// import {Auth, Amplify, Predicates} from 'aws-amplify';
// import { getCurrentUser, AuthUser } from 'aws-amplify/auth';
// import { DataStore, AuthModeStrategyType } from 'aws-amplify/datastore';

const AuthContext = createContext({})
const AuthContextProvider = ({children})=>{

    const [authUser, setAuthUser] = useState(null)
    const [dbUser, setDbUser] = useState(null)
    const sub = authUser?.userId;

    // This is one method to use 'await'
    // const fetchUser = async ()=>{
    //     try{
    //         const res = await getCurrentUser()
    //         console.log(authUser)   
    //         console.log('checking if this is authUser:', authUser) 
    //     }catch(err){
    //         console.log('This is the error',err)
    //     }

    // }

    // useEffect(()=>{
    //     fetchUser()
    //     // getCurrentUser().then((res)=>setAuthUser(res))
    //     // console.log("this is authUser:", authUser)
    //     // console.log('this is sub:', sub)
    // },[]);

     useEffect(() => {
        getCurrentUser().then((res) => {
            setAuthUser(res);
            console.log('Updated authUser:', res);
            console.log('This is sub:',sub)
        }).catch((err) => {
            console.log('Error fetching current user:', err);
        });
    }, []);

    // useEffect(()=>{
    //     DataStore.query(User, (user)=>user.sub.eq(sub)).then((users)=>setDbUser(users[0]))
    //     console.log(dbUser)
    //     console.log('checking if this is dbUser:', dbUser)
    //     // Amplify.Logger.LOG_LEVEL = "DEBUG";
    //     // DataStore.observeQuery(User)
    //     // DataStore.delete(User, Predicates.ALL)
    //     // DataStore.clear()
    // }, [sub])
    useEffect(() => {
        if (sub) {
            DataStore.query(User, (user) => user.sub.eq(sub)).then((users) => {
                setDbUser(users[0]);
                console.log('Updated dbUser:', users[0]);
                console.log('this is dbuser',dbUser)
                // Amplify.Logger.LOG_LEVEL = "DEBUG";
                // DataStore.observeQuery(User)
                // DataStore.delete(User, Predicates.ALL)
                // DataStore.clear()
            }).catch((error) => {
                console.log('Error fetching dbUser:', error);
            });
            console.log('see sub and dbuser:', sub,'dbusernkor:', dbUser)
        }
    }, [sub]);

    // This useEffect is for if I want to do things online only ie, I can delete things in the amplify studio and it will delete locally

    // useEffect(() => {
    //     const subscription = DataStore.observeQuery(
    //         User,
    //         user => user.sub.eq(sub)
    //     ).subscribe(snapshot => {
    //         const { items, isSynced } = snapshot;
    //         console.log(`[Snapshot] item count: ${items.length}, isSynced: ${isSynced}`);
    //         if (items[0]) {
    //             setDbUser(items[0])
    //         }
    //     });

    //     return () => {
    //         subscription.unsubscribe()
    //     }
    // }, [sub])
    // console.log("DB USER: ", dbUser)

    return(
        <AuthContext.Provider value={{authUser, dbUser, sub, setDbUser }}>
            {children}
        </AuthContext.Provider>
    )
}

export default AuthContextProvider;

export const useAuthContext = ()=> useContext(AuthContext)

I can see auth user and sub, but not dbuser

Expected behavior

It is meant to show me the dbuser created but it doesn't. I am unable to access the dbuser, sometimes if, it shows and I update it from my local server, it doesn't show in the remote server (amplify studio).

Reproduction steps

  1. I write this code:
    
    import { createContext, useState,useEffect, useContext } from "react";
    import { confirmResetPassword, getCurrentUser } from 'aws-amplify/auth';
    import { DataStore, Predicates } from 'aws-amplify/datastore';
    import { User } from "../models";
    // import {Auth, Amplify, Predicates} from 'aws-amplify';
    // import { getCurrentUser, AuthUser } from 'aws-amplify/auth';
    // import { DataStore, AuthModeStrategyType } from 'aws-amplify/datastore';

const AuthContext = createContext({})

const AuthContextProvider = ({children})=>{

const [authUser, setAuthUser] = useState(null)
const [dbUser, setDbUser] = useState(null)
const sub = authUser?.userId;

// This is one method to use 'await'
// const fetchUser = async ()=>{
//     try{
//         const res = await getCurrentUser()
//         console.log(authUser)   
//         console.log('checking if this is authUser:', authUser) 
//     }catch(err){
//         console.log('This is the error',err)
//     }

// }

// useEffect(()=>{
//     fetchUser()
//     // getCurrentUser().then((res)=>setAuthUser(res))
//     // console.log("this is authUser:", authUser)
//     // console.log('this is sub:', sub)
// },[]);

 useEffect(() => {
    getCurrentUser().then((res) => {
        setAuthUser(res);
        console.log('Updated authUser:', res);
        console.log('This is sub:',sub)
    }).catch((err) => {
        console.log('Error fetching current user:', err);
    });
}, []);

// useEffect(()=>{
//     DataStore.query(User, (user)=>user.sub.eq(sub)).then((users)=>setDbUser(users[0]))
//     console.log(dbUser)
//     console.log('checking if this is dbUser:', dbUser)
//     // Amplify.Logger.LOG_LEVEL = "DEBUG";
//     // DataStore.observeQuery(User)
//     // DataStore.delete(User, Predicates.ALL)
//     // DataStore.clear()
// }, [sub])
useEffect(() => {
    if (sub) {
        DataStore.query(User, (user) => user.sub.eq(sub)).then((users) => {
            setDbUser(users[0]);
            console.log('Updated dbUser:', users[0]);
            console.log('this is dbuser',dbUser)
            // Amplify.Logger.LOG_LEVEL = "DEBUG";
            // DataStore.observeQuery(User)
            // DataStore.delete(User, Predicates.ALL)
            // DataStore.clear()
        }).catch((error) => {
            console.log('Error fetching dbUser:', error);
        });
        console.log('see sub and dbuser:', sub,'dbusernkor:', dbUser)
    }
}, [sub]);

// This useEffect is for if I want to do things online only ie, I can delete things in the amplify studio and it will delete locally

// useEffect(() => {
//     const subscription = DataStore.observeQuery(
//         User,
//         user => user.sub.eq(sub)
//     ).subscribe(snapshot => {
//         const { items, isSynced } = snapshot;
//         console.log(`[Snapshot] item count: ${items.length}, isSynced: ${isSynced}`);
//         if (items[0]) {
//             setDbUser(items[0])
//         }
//     });

//     return () => {
//         subscription.unsubscribe()
//     }
// }, [sub])
// console.log("DB USER: ", dbUser)

return(
    <AuthContext.Provider value={{authUser, dbUser, sub, setDbUser }}>
        {children}
    </AuthContext.Provider>
)

}

export default AuthContextProvider;

export const useAuthContext = ()=> useContext(AuthContext)

in one folder. note that I have wrapped by main component with `AuthContextProvider`

2. I try to create it here:
```js
// import '@azure/core-asynciterator-polyfill'
import { View, Text, TextInput, Button, Pressable, Alert } from 'react-native'
import React, {useEffect, useState, } from 'react'
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
import styles from './styles'
import { useAuthContext } from '../../contexts/AuthContext'
import { useNavigation } from '@react-navigation/native'
import { signOut } from 'aws-amplify/auth';
import { DataStore } from 'aws-amplify/datastore';
import {User} from '../../models'

const ProfileScreen = () => {

  const {sub, dbUser, setDbUser} = useAuthContext()

  const handleSignOut = async()=> {
    try {
      await signOut();
    } catch (error) {
      console.log('error signing out: ', error);
    }
  }

    const [name, setName] = useState(dbUser?.name || "")
    const [address, setAddress] = useState(dbUser?.address || "")
    const [phoneNumber, setPhoneNumber]= useState(dbUser?.phoneNumber || "")
    const [lat, setLat] = useState(dbUser?.lat.toString() || "0")
    const [lng, setLng] = useState (dbUser?.lng.toString() || "0") 

    const [isFocused, setIsFocused] = useState(false);

    const navigation = useNavigation()

    // Start of Function to Create and Update User

    const createUser = async ()=>{
      try{
        const user = await DataStore.save(new User({
         name, 
         address,
         phoneNumber,
         lat:parseFloat(lat), 
         lng:parseFloat(lng), 
         sub
       })
       );
       console.log("I am User:",user)
       setDbUser(user)
     }catch(e){
       Alert.alert("Error", e.message)
     }
    }

    const updateUser= async ()=>{
      const user = await DataStore.save(User.copyOf(dbUser, (updated)=>{
        updated.name = name;
        updated.address = address;
        updated.phoneNumber = phoneNumber
        updated.lat = parseFloat(lat);
        updated.lng = parseFloat(lng);
      }))
      setDbUser(user)
    }
    // End Of Function to Create and Update User

    // Function to Save Data
    const onSave= async()=>{
      if(dbUser){
        await updateUser()
        navigation.goBack()
      }else{
        await createUser()
        navigation.navigate('HomeScreen')
      }
      // navigation.goBack()
    }

    // function to handle focus
    const handleFocusChange = (focused) => {
      setIsFocused(focused);
    };

    // Start Of GooglePlacesAutoComplete
    const handlePlaceSelect = (data, details = null) => {
      // Extract the address from the selected place
      const selectedAddress = data?.description || details?.formatted_address;

      const selectedAddylat = JSON.stringify(details?.geometry?.location.lat) 

      const selectedAddylng = JSON.stringify(details?.geometry?.location.lng) 

      console.log(selectedAddylng, selectedAddylat)

      // Update the address state
      setAddress(selectedAddress);
      setLat(selectedAddylat)
      setLng(selectedAddylng)

    };
    // End Of GooglePlacesAutoComplete

    return (
    <View style={styles.container}>

      <Text style={styles.title}>Profile</Text>

      <TextInput 
      value={name}
      onChangeText={setName}
      placeholder='Name'
      style={styles.input}
      />

      <TextInput 
      value={address}
      placeholder='Address'
      style={{...styles.input, color: '#04df04'}}
      />

      <View style={isFocused ? styles.gContainerFocused : styles.gContainer}>
        <GooglePlacesAutocomplete
        fetchDetails
        placeholder='Select Address From Here'
        onPress={handlePlaceSelect}
        textInputProps={{
          onFocus:() => handleFocusChange(true),
          onBlur:() => handleFocusChange(false)
        }} 
        styles={{
          textInput:styles.gTextInput,
          textInputContainer:styles.gTextInputContainer,
          listView:styles.glistView,
          poweredContainer:styles.gPoweredContainer
        }}
        query={{
          key: 'key-value',
          language: 'en',
        }}
        />
      </View>

    {/* TextInputs that will be below GooglePlacesAutocomplete */}

      <TextInput
      value={phoneNumber}
      onChangeText={setPhoneNumber}
      placeholder='Phone Number'
      style={styles.input}
      />

      <TextInput 
      value={lat}
      placeholder='Latitude'
      style={styles.input}
      />

      <TextInput 
      value={lng}
      placeholder='Longitude'
      style={styles.input}
      />

      <View style={styles.scrnBtn}>
        {/* Save */}
        <Pressable onPress={onSave} style={styles.saveBackground}>
          <Text style={styles.save}>
            Save
          </Text>
        </Pressable>

        {/* SignOut */}
        <Pressable onPress={handleSignOut} >
          <Text style={styles.signOut}>
            Sign out
          </Text>
        </Pressable>
      </View>

    </View>
  )
}

export default ProfileScreen
  1. When I save for new user, and refresh, It doesn't console. log the database user

Code Snippet

// Put your code below this line.
this is for authcontext:
`import { createContext, useState,useEffect, useContext } from "react";
import { confirmResetPassword, getCurrentUser } from 'aws-amplify/auth';
import { DataStore, Predicates } from 'aws-amplify/datastore';
import { User } from "../models";
// import {Auth, Amplify, Predicates} from 'aws-amplify';
// import { getCurrentUser, AuthUser } from 'aws-amplify/auth';
// import { DataStore, AuthModeStrategyType } from 'aws-amplify/datastore';

const AuthContext = createContext({})

const AuthContextProvider = ({children})=>{

    const [authUser, setAuthUser] = useState(null)
    const [dbUser, setDbUser] = useState(null)
    const sub = authUser?.userId;

    // This is one method to use 'await'
    // const fetchUser = async ()=>{
    //     try{
    //         const res = await getCurrentUser()
    //         console.log(authUser)   
    //         console.log('checking if this is authUser:', authUser) 
    //     }catch(err){
    //         console.log('This is the error',err)
    //     }

    // }

    // useEffect(()=>{
    //     fetchUser()
    //     // getCurrentUser().then((res)=>setAuthUser(res))
    //     // console.log("this is authUser:", authUser)
    //     // console.log('this is sub:', sub)
    // },[]);

     useEffect(() => {
        getCurrentUser().then((res) => {
            setAuthUser(res);
            console.log('Updated authUser:', res);
            console.log('This is sub:',sub)
        }).catch((err) => {
            console.log('Error fetching current user:', err);
        });
    }, []);

    // useEffect(()=>{
    //     DataStore.query(User, (user)=>user.sub.eq(sub)).then((users)=>setDbUser(users[0]))
    //     console.log(dbUser)
    //     console.log('checking if this is dbUser:', dbUser)
    //     // Amplify.Logger.LOG_LEVEL = "DEBUG";
    //     // DataStore.observeQuery(User)
    //     // DataStore.delete(User, Predicates.ALL)
    //     // DataStore.clear()
    // }, [sub])
    useEffect(() => {
        if (sub) {
            DataStore.query(User, (user) => user.sub.eq(sub)).then((users) => {
                setDbUser(users[0]);
                console.log('Updated dbUser:', users[0]);
                console.log('this is dbuser',dbUser)
                // Amplify.Logger.LOG_LEVEL = "DEBUG";
                // DataStore.observeQuery(User)
                // DataStore.delete(User, Predicates.ALL)
                // DataStore.clear()
            }).catch((error) => {
                console.log('Error fetching dbUser:', error);
            });
            console.log('see sub and dbuser:', sub,'dbusernkor:', dbUser)
        }
    }, [sub]);

    // This useEffect is for if I want to do things online only ie, I can delete things in the amplify studio and it will delete locally

    // useEffect(() => {
    //     const subscription = DataStore.observeQuery(
    //         User,
    //         user => user.sub.eq(sub)
    //     ).subscribe(snapshot => {
    //         const { items, isSynced } = snapshot;
    //         console.log(`[Snapshot] item count: ${items.length}, isSynced: ${isSynced}`);
    //         if (items[0]) {
    //             setDbUser(items[0])
    //         }
    //     });

    //     return () => {
    //         subscription.unsubscribe()
    //     }
    // }, [sub])
    // console.log("DB USER: ", dbUser)

    return(
        <AuthContext.Provider value={{authUser, dbUser, sub, setDbUser }}>
            {children}
        </AuthContext.Provider>
    )
}

export default AuthContextProvider;

export const useAuthContext = ()=> useContext(AuthContext)

this is for the profile screen where I create and edit the dbuser:

// import '@azure/core-asynciterator-polyfill'
import { View, Text, TextInput, Button, Pressable, Alert } from 'react-native'
import React, {useEffect, useState, } from 'react'
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
import styles from './styles'
import { useAuthContext } from '../../contexts/AuthContext'
import { useNavigation } from '@react-navigation/native'
import { signOut } from 'aws-amplify/auth';
import { DataStore } from 'aws-amplify/datastore';
import {User} from '../../models'

const ProfileScreen = () => {

  const {sub, dbUser, setDbUser} = useAuthContext()

  const handleSignOut = async()=> {
    try {
      await signOut();
    } catch (error) {
      console.log('error signing out: ', error);
    }
  }

    const [name, setName] = useState(dbUser?.name || "")
    const [address, setAddress] = useState(dbUser?.address || "")
    const [phoneNumber, setPhoneNumber]= useState(dbUser?.phoneNumber || "")
    const [lat, setLat] = useState(dbUser?.lat.toString() || "0")
    const [lng, setLng] = useState (dbUser?.lng.toString() || "0") 

    const [isFocused, setIsFocused] = useState(false);

    const navigation = useNavigation()

    // Start of Function to Create and Update User

    const createUser = async ()=>{
      try{
        const user = await DataStore.save(new User({
         name, 
         address,
         phoneNumber,
         lat:parseFloat(lat), 
         lng:parseFloat(lng), 
         sub
       })
       );
       console.log("I am User:",user)
       setDbUser(user)
     }catch(e){
       Alert.alert("Error", e.message)
     }
    }

    const updateUser= async ()=>{
      const user = await DataStore.save(User.copyOf(dbUser, (updated)=>{
        updated.name = name;
        updated.address = address;
        updated.phoneNumber = phoneNumber
        updated.lat = parseFloat(lat);
        updated.lng = parseFloat(lng);
      }))
      setDbUser(user)
    }
    // End Of Function to Create and Update User

    // Function to Save Data
    const onSave= async()=>{
      if(dbUser){
        await updateUser()
        navigation.goBack()
      }else{
        await createUser()
        navigation.navigate('HomeScreen')
      }
      // navigation.goBack()
    }

    // function to handle focus
    const handleFocusChange = (focused) => {
      setIsFocused(focused);
    };

    // Start Of GooglePlacesAutoComplete
    const handlePlaceSelect = (data, details = null) => {
      // Extract the address from the selected place
      const selectedAddress = data?.description || details?.formatted_address;

      const selectedAddylat = JSON.stringify(details?.geometry?.location.lat) 

      const selectedAddylng = JSON.stringify(details?.geometry?.location.lng) 

      console.log(selectedAddylng, selectedAddylat)

      // Update the address state
      setAddress(selectedAddress);
      setLat(selectedAddylat)
      setLng(selectedAddylng)

    };
    // End Of GooglePlacesAutoComplete

    return (
    <View style={styles.container}>

      <Text style={styles.title}>Profile</Text>

      <TextInput 
      value={name}
      onChangeText={setName}
      placeholder='Name'
      style={styles.input}
      />

      <TextInput 
      value={address}
      placeholder='Address'
      style={{...styles.input, color: '#04df04'}}
      />

      <View style={isFocused ? styles.gContainerFocused : styles.gContainer}>
        <GooglePlacesAutocomplete
        fetchDetails
        placeholder='Select Address From Here'
        onPress={handlePlaceSelect}
        textInputProps={{
          onFocus:() => handleFocusChange(true),
          onBlur:() => handleFocusChange(false)
        }} 
        styles={{
          textInput:styles.gTextInput,
          textInputContainer:styles.gTextInputContainer,
          listView:styles.glistView,
          poweredContainer:styles.gPoweredContainer
        }}
        query={{
          key: 'AIzaSyADZpw6XnHY',
          language: 'en',
        }}
        />
      </View>

    {/* TextInputs that will be below GooglePlacesAutocomplete */}

      <TextInput
      value={phoneNumber}
      onChangeText={setPhoneNumber}
      placeholder='Phone Number'
      style={styles.input}
      />

      <TextInput 
      value={lat}
      placeholder='Latitude'
      style={styles.input}
      />

      <TextInput 
      value={lng}
      placeholder='Longitude'
      style={styles.input}
      />

      <View style={styles.scrnBtn}>
        {/* Save */}
        <Pressable onPress={onSave} style={styles.saveBackground}>
          <Text style={styles.save}>
            Save
          </Text>
        </Pressable>

        {/* SignOut */}
        <Pressable onPress={handleSignOut} >
          <Text style={styles.signOut}>
            Sign out
          </Text>
        </Pressable>
      </View>

    </View>
  )
}

export default ProfileScreen

Log output

``` // Put your logs below this line ``` `[WARN] 33:53.414 DataStore - subscriptionError Connection failed: {"errors":[{"message":"Validation error of type FieldUndefined: Field '_version'` `{"ACTIVITY_NULL": 4, "PERMISSION_DENIED": 1, "POSITION_UNAVAILABLE": 2, "TIMEOUT": 3, "code": 3, "message": "Location request timed out"} `

aws-exports.js

/ eslint-disable / // WARNING: DO NOT EDIT. This file is automatically generated by AWS Amplify. It will be overwritten.

const awsmobile = { "aws_project_region": **, "aws_appsync_graphqlEndpoint": **, "aws_appsync_region": **, "aws_appsync_authenticationType": **, "aws_appsync_apiKey": **, "aws_cognito_identity_pool_id": **, "aws_cognito_region": **, "aws_user_pools_id": **, "aws_user_pools_web_client_id": **, "oauth": {}, "aws_cognito_username_attributes": [ "EMAIL" ], "aws_cognito_social_providers": [], "aws_cognito_signup_attributes": [], "aws_cognito_mfa_configuration": "OFF", "aws_cognito_mfa_types": [ "SMS" ], "aws_cognito_password_protection_settings": { "passwordPolicyMinLength": 8, "passwordPolicyCharacters": [ "REQUIRES_NUMBERS" ] }, "aws_cognito_verification_mechanisms": [ "EMAIL" ] };

export default awsmobile;

Manual configuration

No response

Additional configuration

Nothing

Mobile Device

Samsung

Mobile Operating System

No response

Mobile Browser

No response

Mobile Browser Version

No response

Additional information and screenshots

Nothing

cwomack commented 4 months ago

Hello, @elkee2003 šŸ‘‹. I've got quite a few questions for you on this issue to see if we can figure out what's going on and unblock you. I'm not exactly sure what is failing here, so can you help break down/clarify the following:

Any additional and relevant areas where you can include more outputs from the console logs (specifically the DataStore operations) would be helpful as well. Not sure if there's a minimal sample repo that you can provide as well, but if you have a more basic example without all the commented out code that would be great!

elkee2003 commented 4 months ago

Hello, @elkee2003 šŸ‘‹. I've got quite a few questions for you on this issue to see if we can figure out what's going on and unblock you. I'm not exactly sure what is failing here, so can you help break down/clarify the following:

  • What response are you getting when you call getCurrentUser()`? Is it throwing an error or can you log the user returned?
  • Have you made any changes that potentially haven't been pushed yet via amplify push command?
  • Where is this error coming from? LOG {"ACTIVITY_NULL": 4, "PERMISSION_DENIED": 1, "POSITION_UNAVAILABLE": 2, "TIMEOUT": 3, "code": 3, "message": "Location request timed out"}
  • Can you provide a little more details on the problem described here? "I am unable to access the dbuser, sometimes if, it shows and I update it from my local server, it doesn't show in the remote server (amplify studio)."

Any additional and relevant areas where you can include more outputs from the console logs (specifically the DataStore operations) would be helpful as well. Not sure if there's a minimal sample repo that you can provide as well, but if you have a more basic example without all the commented out code that would be great!

elkee2003 commented 3 months ago

Hello, @elkee2003 šŸ‘‹. I've got quite a few questions for you on this issue to see if we can figure out what's going on and unblock you. I'm not exactly sure what is failing here, so can you help break down/clarify the following:

  • What response are you getting when you call getCurrentUser()`? Is it throwing an error or can you log the user returned?
  • Have you made any changes that potentially haven't been pushed yet via amplify push command?
  • Where is this error coming from? LOG {"ACTIVITY_NULL": 4, "PERMISSION_DENIED": 1, "POSITION_UNAVAILABLE": 2, "TIMEOUT": 3, "code": 3, "message": "Location request timed out"}
  • Can you provide a little more details on the problem described here? "I am unable to access the dbuser, sometimes if, it shows and I update it from my local server, it doesn't show in the remote server (amplify studio)."

Any additional and relevant areas where you can include more outputs from the console logs (specifically the DataStore operations) would be helpful as well. Not sure if there's a minimal sample repo that you can provide as well, but if you have a more basic example without all the commented out code that would be great!

Hello, please is there a solution to my problem

elkee2003 commented 3 months ago

Please I need help

chrisbonifacio commented 3 months ago

Hi @elkee2003 can you confirm that you have Conflict Detection enabled on your API? If you don't, that would explain the subscription error. DataStore expects specific fields to exist on the schema such as _version, _lastChangedAt, and _deleted which are automatically added if Conflict Detection is enabled when compiling/deploying the schema.

Looking at the logic you have to create and update a user, it seems to make sense and should work even if there is a misconfiguration as I mentioned above. To better support you, can you please explain the use case and exactly what you are trying to do so that we can provide a working sample?

It seems you are trying to create a context/provider where components can access a user record stored in state. Have you checked if that record is persisting to DynamoDB when saving? You can check the network activity for the mutation response or query for the record in the DynamoDB console's Items explorer. Also, are you able to query for the record by the sub or even id separate from the context/provider pattern?

Lastly, if you want to sign in/out and keep the state in sync with the auth status of the user, you should use the Hub utility to listen for auth events and clear your auth state and/or local database in response to auth events.

https://docs.amplify.aws/react/build-a-backend/utilities/hub/

elkee2003 commented 3 months ago

Hi @elkee2003 can you confirm that you have Conflict Detection enabled on your API? If you don't, that would explain the subscription error. DataStore expects specific fields to exist on the schema such as _version, _lastChangedAt, and _deleted which are automatically added if Conflict Detection is enabled when compiling/deploying the schema.

Looking at the logic you have to create and update a user, it seems to make sense and should work even if there is a misconfiguration as I mentioned above. To better support you, can you please explain the use case and exactly what you are trying to do so that we can provide a working sample?

It seems you are trying to create a context/provider where components can access a user record stored in state. Have you checked if that record is persisting to DynamoDB when saving? You can check the network activity for the mutation response or query for the record in the DynamoDB console's Items explorer. Also, are you able to query for the record by the sub or even id separate from the context/provider pattern?

Lastly, if you want to sign in/out and keep the state in sync with the auth status of the user, you should use the Hub utility to listen for auth events and clear your auth state and/or local database in response to auth events.

https://docs.amplify.aws/react/build-a-backend/utilities/hub/

The conflict detection is enabled, as seen in the screenshot: Screenshot (89)

I have a question: What should I use as the conflict resolution strategy? Automerge or Optimistic Concurrency: Screenshot (90)

What I want to do is to simply create a user and update a user, the only the difference is that I access the authenticated user in AuthContext and the database user, so that I will be able to access them everywhere I want in my application. However, I am unable to access the database user, although I can access the authenticated user and even the sub of the authenticated user anywhere and anytime in my application.

I am trying to create a context provider, where components can access the a user's record stored in state. The issue is, even if i can see the dbuser that I have created in appsync (remote server), in vs code, it still shows that the dbuser is null.

This is the evidence: In this screenshot you can clearly see a dbuser: Screenshot (91)

In this other screenshot, you can see in my code that I am trying to access the user field at an index of 0 with setDbUser, which accesses it comfortably as seen in my console. However, I cannot access dbUser after console.logging it, as also seen in my console that dbUser is null Screenshot (92)

I can see the records in DynamoDb: Screenshot (94) Screenshot (95)

I plead that you help me find a solution to this, even if it means us video calling and working on it at the same time, or I share my screen with you so you can have a better understanding of what I am facing. I have been having issues with aws amplify for more than a year now, especially with datastore. Thank you as you look into my problem.

elkee2003 commented 3 months ago

Hi @elkee2003 can you confirm that you have Conflict Detection enabled on your API? If you don't, that would explain the subscription error. DataStore expects specific fields to exist on the schema such as _version, _lastChangedAt, and _deleted which are automatically added if Conflict Detection is enabled when compiling/deploying the schema.

Looking at the logic you have to create and update a user, it seems to make sense and should work even if there is a misconfiguration as I mentioned above. To better support you, can you please explain the use case and exactly what you are trying to do so that we can provide a working sample?

It seems you are trying to create a context/provider where components can access a user record stored in state. Have you checked if that record is persisting to DynamoDB when saving? You can check the network activity for the mutation response or query for the record in the DynamoDB console's Items explorer. Also, are you able to query for the record by the sub or even id separate from the context/provider pattern?

Lastly, if you want to sign in/out and keep the state in sync with the auth status of the user, you should use the Hub utility to listen for auth events and clear your auth state and/or local database in response to auth events.

https://docs.amplify.aws/react/build-a-backend/utilities/hub/

Hello good day, just a reminder that I'm still waiting

elkee2003 commented 2 months ago

Hi @elkee2003 can you confirm that you have Conflict Detection enabled on your API? If you don't, that would explain the subscription error. DataStore expects specific fields to exist on the schema such as _version, _lastChangedAt, and _deleted which are automatically added if Conflict Detection is enabled when compiling/deploying the schema.

Looking at the logic you have to create and update a user, it seems to make sense and should work even if there is a misconfiguration as I mentioned above. To better support you, can you please explain the use case and exactly what you are trying to do so that we can provide a working sample?

It seems you are trying to create a context/provider where components can access a user record stored in state. Have you checked if that record is persisting to DynamoDB when saving? You can check the network activity for the mutation response or query for the record in the DynamoDB console's Items explorer. Also, are you able to query for the record by the sub or even id separate from the context/provider pattern?

Lastly, if you want to sign in/out and keep the state in sync with the auth status of the user, you should use the Hub utility to listen for auth events and clear your auth state and/or local database in response to auth events.

https://docs.amplify.aws/react/build-a-backend/utilities/hub/

Hello good day, just a reminder that I'm still waiting

Please I am still waiting for a response

elkee2003 commented 2 months ago

Hi @elkee2003 can you confirm that you have Conflict Detection enabled on your API? If you don't, that would explain the subscription error. DataStore expects specific fields to exist on the schema such as _version, _lastChangedAt, and _deleted which are automatically added if Conflict Detection is enabled when compiling/deploying the schema.

Looking at the logic you have to create and update a user, it seems to make sense and should work even if there is a misconfiguration as I mentioned above. To better support you, can you please explain the use case and exactly what you are trying to do so that we can provide a working sample?

It seems you are trying to create a context/provider where components can access a user record stored in state. Have you checked if that record is persisting to DynamoDB when saving? You can check the network activity for the mutation response or query for the record in the DynamoDB console's Items explorer. Also, are you able to query for the record by the sub or even id separate from the context/provider pattern?

Lastly, if you want to sign in/out and keep the state in sync with the auth status of the user, you should use the Hub utility to listen for auth events and clear your auth state and/or local database in response to auth events.

https://docs.amplify.aws/react/build-a-backend/utilities/hub/

Hello just a kind reminder that I still await a response

renebrandel commented 2 months ago

@elkee2003 - can you provide your GraphQL schema? I suspect there's two potential issues 1/ the authorization rules aren't configured in a way that'll make the data accessible. 2/ the "query" call is async to the sync process, so there's a potential for a race condition even if the data has been synced. (I also recommend you to call DataStore.clear() and stop/start.

elkee2003 commented 2 months ago

@elkee2003 - can you provide your GraphQL schema? I suspect there's two potential issues 1/ the authorization rules aren't configured in a way that'll make the data accessible. 2/ the "query" call is async to the sync process, so there's a potential for a race condition even if the data has been synced. (I also recommend you to call DataStore.clear() and stop/start.

I got this from amplify > backend > api > schema.graphql: Screenshot (96) This is the code: `enum AtuaType { WALK BIKE CAR GROUP }

enum OrderStatus { READY_FOR_PICKUP ACCEPTED PICKEDUP DELIVERED }

type Order @model @auth(rules: [{allow: public}]) { id: ID! recipientName: String! recipientNumber: String! orderDetails: String total: Float originPlace: String destinationPlace: String atuaType: AtuaType status: OrderStatus userID: ID! @index(name: "byUser") }

type User @model @auth(rules: [{allow: public}]) { id: ID! sub: String! name: String phoneNumber: String address: String lng: Float lat: Float Orders: [Order] @hasMany(indexName: "byUser", fields: ["id"]) type: AtuaType } `

I got this from amplify > backend > api > Atua > build > schema.graphql: Screenshot (97) This is the code: `enum AtuaType { WALK BIKE CAR GROUP }

enum OrderStatus { READY_FOR_PICKUP ACCEPTED PICKEDUP DELIVERED }

type Order @aws_iam @aws_api_key { id: ID! recipientName: String! recipientNumber: String! orderDetails: String total: Float originPlace: String destinationPlace: String atuaType: AtuaType status: OrderStatus userID: ID! createdAt: AWSDateTime! updatedAt: AWSDateTime! _version: Int! _deleted: Boolean _lastChangedAt: AWSTimestamp! }

type User @aws_iam @aws_api_key { id: ID! sub: String! name: String phoneNumber: String address: String lng: Float lat: Float Orders(filter: ModelOrderFilterInput, sortDirection: ModelSortDirection, limit: Int, nextToken: String): ModelOrderConnection type: AtuaType createdAt: AWSDateTime! updatedAt: AWSDateTime! _version: Int! _deleted: Boolean _lastChangedAt: AWSTimestamp! }

input ModelStringInput { ne: String eq: String le: String lt: String ge: String gt: String contains: String notContains: String between: [String] beginsWith: String attributeExists: Boolean attributeType: ModelAttributeTypes size: ModelSizeInput }

input ModelIntInput { ne: Int eq: Int le: Int lt: Int ge: Int gt: Int between: [Int] attributeExists: Boolean attributeType: ModelAttributeTypes }

input ModelFloatInput { ne: Float eq: Float le: Float lt: Float ge: Float gt: Float between: [Float] attributeExists: Boolean attributeType: ModelAttributeTypes }

input ModelBooleanInput { ne: Boolean eq: Boolean attributeExists: Boolean attributeType: ModelAttributeTypes }

input ModelIDInput { ne: ID eq: ID le: ID lt: ID ge: ID gt: ID contains: ID notContains: ID between: [ID] beginsWith: ID attributeExists: Boolean attributeType: ModelAttributeTypes size: ModelSizeInput }

input ModelSubscriptionStringInput { ne: String eq: String le: String lt: String ge: String gt: String contains: String notContains: String between: [String] beginsWith: String in: [String] notIn: [String] }

input ModelSubscriptionIntInput { ne: Int eq: Int le: Int lt: Int ge: Int gt: Int between: [Int] in: [Int] notIn: [Int] }

input ModelSubscriptionFloatInput { ne: Float eq: Float le: Float lt: Float ge: Float gt: Float between: [Float] in: [Float] notIn: [Float] }

input ModelSubscriptionBooleanInput { ne: Boolean eq: Boolean }

input ModelSubscriptionIDInput { ne: ID eq: ID le: ID lt: ID ge: ID gt: ID contains: ID notContains: ID between: [ID] beginsWith: ID in: [ID] notIn: [ID] }

enum ModelAttributeTypes { binary binarySet bool list map number numberSet string stringSet _null }

input ModelSizeInput { ne: Int eq: Int le: Int lt: Int ge: Int gt: Int between: [Int] }

enum ModelSortDirection { ASC DESC }

type ModelOrderConnection @aws_api_key @aws_iam { items: [Order]! nextToken: String startedAt: AWSTimestamp }

input ModelAtuaTypeInput { eq: AtuaType ne: AtuaType }

input ModelOrderStatusInput { eq: OrderStatus ne: OrderStatus }

input ModelOrderFilterInput { id: ModelIDInput recipientName: ModelStringInput recipientNumber: ModelStringInput orderDetails: ModelStringInput total: ModelFloatInput originPlace: ModelStringInput destinationPlace: ModelStringInput atuaType: ModelAtuaTypeInput status: ModelOrderStatusInput userID: ModelIDInput and: [ModelOrderFilterInput] or: [ModelOrderFilterInput] not: ModelOrderFilterInput _deleted: ModelBooleanInput }

type Query { getOrder(id: ID!): Order @aws_api_key @aws_iam listOrders(filter: ModelOrderFilterInput, limit: Int, nextToken: String): ModelOrderConnection @aws_api_key @aws_iam syncOrders(filter: ModelOrderFilterInput, limit: Int, nextToken: String, lastSync: AWSTimestamp): ModelOrderConnection @aws_api_key @aws_iam ordersByUserID(userID: ID!, sortDirection: ModelSortDirection, filter: ModelOrderFilterInput, limit: Int, nextToken: String): ModelOrderConnection @aws_api_key @aws_iam getUser(id: ID!): User @aws_api_key @aws_iam listUsers(filter: ModelUserFilterInput, limit: Int, nextToken: String): ModelUserConnection @aws_api_key @aws_iam syncUsers(filter: ModelUserFilterInput, limit: Int, nextToken: String, lastSync: AWSTimestamp): ModelUserConnection @aws_api_key @aws_iam }

input ModelOrderConditionInput { recipientName: ModelStringInput recipientNumber: ModelStringInput orderDetails: ModelStringInput total: ModelFloatInput originPlace: ModelStringInput destinationPlace: ModelStringInput atuaType: ModelAtuaTypeInput status: ModelOrderStatusInput userID: ModelIDInput and: [ModelOrderConditionInput] or: [ModelOrderConditionInput] not: ModelOrderConditionInput _deleted: ModelBooleanInput }

input CreateOrderInput { id: ID recipientName: String! recipientNumber: String! orderDetails: String total: Float originPlace: String destinationPlace: String atuaType: AtuaType status: OrderStatus userID: ID! _version: Int }

input UpdateOrderInput { id: ID! recipientName: String recipientNumber: String orderDetails: String total: Float originPlace: String destinationPlace: String atuaType: AtuaType status: OrderStatus userID: ID _version: Int }

input DeleteOrderInput { id: ID! _version: Int }

type Mutation { createOrder(input: CreateOrderInput!, condition: ModelOrderConditionInput): Order @aws_api_key @aws_iam updateOrder(input: UpdateOrderInput!, condition: ModelOrderConditionInput): Order @aws_api_key @aws_iam deleteOrder(input: DeleteOrderInput!, condition: ModelOrderConditionInput): Order @aws_api_key @aws_iam createUser(input: CreateUserInput!, condition: ModelUserConditionInput): User @aws_api_key @aws_iam updateUser(input: UpdateUserInput!, condition: ModelUserConditionInput): User @aws_api_key @aws_iam deleteUser(input: DeleteUserInput!, condition: ModelUserConditionInput): User @aws_api_key @aws_iam }

input ModelSubscriptionOrderFilterInput { id: ModelSubscriptionIDInput recipientName: ModelSubscriptionStringInput recipientNumber: ModelSubscriptionStringInput orderDetails: ModelSubscriptionStringInput total: ModelSubscriptionFloatInput originPlace: ModelSubscriptionStringInput destinationPlace: ModelSubscriptionStringInput atuaType: ModelSubscriptionStringInput status: ModelSubscriptionStringInput userID: ModelSubscriptionIDInput and: [ModelSubscriptionOrderFilterInput] or: [ModelSubscriptionOrderFilterInput] _deleted: ModelBooleanInput }

type Subscription { onCreateOrder(filter: ModelSubscriptionOrderFilterInput): Order @aws_subscribe(mutations: ["createOrder"]) @aws_api_key @aws_iam onUpdateOrder(filter: ModelSubscriptionOrderFilterInput): Order @aws_subscribe(mutations: ["updateOrder"]) @aws_api_key @aws_iam onDeleteOrder(filter: ModelSubscriptionOrderFilterInput): Order @aws_subscribe(mutations: ["deleteOrder"]) @aws_api_key @aws_iam onCreateUser(filter: ModelSubscriptionUserFilterInput): User @aws_subscribe(mutations: ["createUser"]) @aws_api_key @aws_iam onUpdateUser(filter: ModelSubscriptionUserFilterInput): User @aws_subscribe(mutations: ["updateUser"]) @aws_api_key @aws_iam onDeleteUser(filter: ModelSubscriptionUserFilterInput): User @aws_subscribe(mutations: ["deleteUser"]) @aws_api_key @aws_iam }

type ModelUserConnection @aws_api_key @aws_iam { items: [User]! nextToken: String startedAt: AWSTimestamp }

input ModelUserFilterInput { id: ModelIDInput sub: ModelStringInput name: ModelStringInput phoneNumber: ModelStringInput address: ModelStringInput lng: ModelFloatInput lat: ModelFloatInput type: ModelAtuaTypeInput and: [ModelUserFilterInput] or: [ModelUserFilterInput] not: ModelUserFilterInput _deleted: ModelBooleanInput }

input ModelUserConditionInput { sub: ModelStringInput name: ModelStringInput phoneNumber: ModelStringInput address: ModelStringInput lng: ModelFloatInput lat: ModelFloatInput type: ModelAtuaTypeInput and: [ModelUserConditionInput] or: [ModelUserConditionInput] not: ModelUserConditionInput _deleted: ModelBooleanInput }

input CreateUserInput { id: ID sub: String! name: String phoneNumber: String address: String lng: Float lat: Float type: AtuaType _version: Int }

input UpdateUserInput { id: ID! sub: String name: String phoneNumber: String address: String lng: Float lat: Float type: AtuaType _version: Int }

input DeleteUserInput { id: ID! _version: Int }

input ModelSubscriptionUserFilterInput { id: ModelSubscriptionIDInput sub: ModelSubscriptionStringInput name: ModelSubscriptionStringInput phoneNumber: ModelSubscriptionStringInput address: ModelSubscriptionStringInput lng: ModelSubscriptionFloatInput lat: ModelSubscriptionFloatInput type: ModelSubscriptionStringInput and: [ModelSubscriptionUserFilterInput] or: [ModelSubscriptionUserFilterInput] _deleted: ModelBooleanInput } `

chrisbonifacio commented 2 months ago

Hi @elkee2003, thank you for sharing your schema. We will try to reproduce the issue on our end and report back with findings soon.

chrisbonifacio commented 2 months ago

In the meantime, if you can provide a small sample app or can invite me to your repo to build the app locally please do. It would help to speed up the reproduction as I notice you are building a React Native app and will have to try to recreate the environment including package versions, amplify backend, etc

elkee2003 commented 2 months ago

In the meantime, if you can provide a small sample app or can invite me to your repo to build the app locally please do. It would help to speed up the reproduction as I notice you are building a React Native app and will have to try to recreate the environment including package versions, amplify backend, etc

Done!