I have a react native app build with AWS Amplify. In this I have a custom authentication flow creating a cognito user and a post confirmation lambda trigger creating a real dynamoDB user. But the problem arise when I want to query this real user in my app home screen. At present I do it as follows, I first get the current authenticated user from cognito and then from the data receive I query real database user, but sometimes at first this fail to get the user but when I refresh the screen I get the user back. I want to know the best way to do this ?
My code,
import { Auth } from "aws-amplify";
import { DataStore} from '@aws-amplify/datastore';
import { User } from "../src/models";
const [user , setUser] = useState <User[]>([]);
const [ready, setReady] = useState(false);
const getUser = async () => {
try{
const userData = await Auth.currentAuthenticatedUser();
const currentUserPhone = userData.attributes.phone_number
if(currentUserPhone){
await DataStore.query(User, d => d.Phonenumb("eq", currentUserPhone)).then(setUser);
console.log("getting user in home");
setReady(true);
} else{
setReady(false);
}
} catch(e){
setReady(false);
console.log(e)
}
}
useEffect(() => {
getUser();
}, []);
return(
<View>
{ready === true &&(<Text>Hello {user?.name}</Text>)}
{ready === false &&(<Text>No user</Text>)}
</View>
)
Ensure data is synced before querying. Call start
and listen for ready
event.
await DataStore.start();
Hub.listen('datastore', (data) => {
const { event } = data.payload;
if (event === "ready") {
// TODO
}
})