talamcol
talamcol

Reputation: 3

firebase currentUser is null on page reload

I'm using firebase for authentication. Everytime before I do a request to the backend I request for the idToken.

service.interceptors.request.use(async request => {
  const token = await firebase.auth().currentUser.getIdToken();
  if (!token && request.url !== '/signIn' && request.url !== '/register') {
    toast.error('Not authenticated');
    return;
  }
  request.headers.Authorization = 'Bearer ' + token;
  return request;
});

Additionally I have a request to the backend that will run in the mounted hook of my vue component.

mounted() {
   plantService.getPlants().then(data => (this.suspicionList = data));
}

Usually, this works but the problem is, when I refresh the page, firebase.auth().currentUser is null and the request will fail thus not returning any data.

I already tried creating a computed property and observe that one in a watcher. But not working. Also, I have an observer for the user in my main.js file like this:

firebase.auth().onAuthStateChanged(user => {
  store.dispatch('FETCH_USER', user);
});

Anyone has an idea?

Thanks!

Upvotes: 0

Views: 1284

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83093

If I correctly understand your problem, the following should do the trick:

mounted() {
    firebase.auth().onAuthStateChanged(user => {
        if (user) {
           plantService.getPlants().then(data => (this.suspicionList = data));
        }
    });
}

Upvotes: 2

Related Questions