meteorrn / meteor-react-native

Meteor client for React Native matching Meteor Spec
https://guide.meteor.com/react-native.html
Other
59 stars 31 forks source link

Subscribe to user account without component #68

Closed odesey closed 3 years ago

odesey commented 3 years ago

Is it possible to load a user account and subscribe to user account data without using useTracker and a component?

Similar to https://github.com/gregivy/simpleddp

I have a react-native app, and before the app is loaded I need to see if the user is logged in and then load the appropriate UI.

How can I do this using the meteor-react-native package?

Thanks.

TheRealNate commented 3 years ago

Hi @odesey,

If you're looking for a callback, you can use this:

import { Accounts } from '@meteorrn/core';

Accounts.onLogin(() => {
    const user = Meteor.user();
    ...
});

If you just want to check login as soon as the app loads, you won't be able to. The user is not considered logged in until they've sent their token to the server and gotten back confirmation from the server. However, what I can recommend is storing a flag using something like AsyncStorage.

import AsyncStorage from '@react-native-async-storage/async-storage';

Accounts.onLogin(() => {
    AsyncStorage.setItem("userId", Meteor.user()._id);
});

// To check if logged in
await AsyncStorage.getItem("userId"); // async
AsyncStorage.getItem("userId").then(() => {
  // ...
}); // promise

Does this answer your question?

odesey commented 3 years ago

I think that your suggestion will solve 1/2 of my question (thanks).

The second part is, can I subscribe to a publication (in this case the user account data) without using useTracker and a component?

Currently, I am using the simple-ddp package and I subscribe to my user's data in my init function if they are logged in like so:

const server = new simpleddp(options, [simpleDDPLogin]);

initFunc = () => {
  let userSub = server.subscribe('user');
  await userSub.ready();

  // more stuff here

  }

Lastly, how can I handle not being able to connect to my Meteor server when calling Meteor.connect()? In the event of a network interruption, I would need some way of knowing that the connection has failed.

Thanks.

TheRealNate commented 3 years ago

Hey @odesey,

Absolutely. The reason you'd usually do your subscriptions in a useTracker or withTracker is because it will automatically stop the subscription if the component gets unmounted. But you don't have to: you can subscribe anywhere you want. And if you store the handle you can always call .stop();

Our spec works exactly like the Meteor spec. All of the available methods do not require useTracker or withTracker.

I'm happy to answer any more questions you have: I'm just going to convert this into a discussion since its a Q&A not a bug.

Thanks!