aws-amplify / amplify-studio

AWS Amplify Studio (Formerly Admin UI)
136 stars 31 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"} #1106

Closed elkee2003 closed 8 months ago

elkee2003 commented 8 months ago

Describe the feature you'd like to request

When I try to save or have access to the database user, I am unable to access it. For example, if I try to save a user, sometimes it doesn't save. If it eventually saves, if I try to edit it from my app, and save, it doesn't reflect in amplify studio.

Describe your use case and how the feature would improve your experience.

I am setting database user here: `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 am trying to create or edit it here: `// 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: 'AIY',
      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`

However, most of the times, it is unable to access the database user to make changes.

Describe alternatives you've considered

I have considered doing amplify update api, automerge update, amplify codegen models and then amplify push, hoping i will be able to automatically access the database in the future, but I can't access it.

Additional context

No response

github-actions[bot] commented 8 months ago

⚠️COMMENT VISIBILITY WARNING⚠️

Comments on closed issues are hard for our team to see. If you need more assistance, please open a new issue that references this one. If you wish to keep having a conversation with other community members under this issue feel free to do so.