'AWS Datastore doesnt query when app oppens for the first time

I use Datastore from Aws-amplify. I have a problem .The problem occurs only when app opens for the first time(when I wipe data of device/reinstall ). Data is loaded only when I reloaded app again. this is for example the code from App.js console.log(user) say it is undefined. When i reloaded, everthing is ok(problem is only if I reinstall app/wipe data of device)

This is example of code from App.js , console.log(user) show me undefinded. When i reload app, everything is ok. Also other query doesnt work, like Posts etc. Always I need reload app, and then it works

const App = () => {
  useEffect(() => {
    const saveUsertoDB = async () => {
      //get user from cognito
      const userInfo = await Auth.currentAuthenticatedUser();
      if (!userInfo) {
        return;
      }
      console.log(userInfo);
      const userId = userInfo.attributes.sub;
      console.log(userId);
      //check if user exist in DB
      const user = (await DataStore.query(User)).find(
        user => user.sub === userId,
      );
      console.log(user);
      //if not save user to db
      if (!user) {
        await DataStore.save(
          new User({
            sub: userId,
            name: userInfo.attributes.email,
          }),
        );
      } else {
        console.warn('User already exist in DB');
      }
    };
    saveUsertoDB();
  }, []);

What can be a problem and solution?



Solution 1:[1]

Datastore queries always run against the local store. You mention that the problem happens after you clear the local store. When the app is started with no local data it doesn't start to sync until your execute the first query, which will likely not find anything yet.

To resolve your issue, try using DataStore.start at the beginning of app startup and then monitor the Amplify hub for the Datastore ready event before continuing the app. This will ensure that all data is in sync locally before you execute the query.

More details in the doc for events.

Solution 2:[2]

I solved the problem waiting for DataStore Load before anything

check this gist:

https://gist.github.com/pptavozl/b345a23f0eb3a5698917ea9ee3f60b96

Solution 3:[3]

One option is to wait for the ready event from the Hub:

// Create listener
const listener = Hub.listen("datastore", async hubData => {
  const  { event, data } = hubData.payload;
  if (event === "ready") {
    // do something here once the data is synced from the cloud
  }
})

// Remove listener
listener();

Another handy option is to use the relatively new observeQuery() method, which provides some nice syntactic sugar over calling query() followed by observe():

const subscription = DataStore.observeQuery(
  Post,
  p => p.title("beginsWith", "post").rating("gt", 10),
  {
    sort: s => s.rating(SortDirection.ASCENDING)
  }
).subscribe(snapshot => {
  const { items, isSynced } = snapshot;
  console.log(`[Snapshot] item count: ${items.length}, isSynced: ${isSynced}`);
});

Other than those two main options, you would want to manually query() and then observe() for updates over your selection criteria.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 julie
Solution 2 GusZL
Solution 3 svidgen