Nuxt Fire / Firebase Vuex does not recognize $fireDb

Currently, I am utilizing Nuxt JS 2.9.2 for constructing a Javascript application. The application incorporates Firebase integration through the Nuxt Fire module, as well as Vuex for managing state and authentication.

The project has been successfully configured, allowing me to create users, log them in, and log them out.

My current objective is to save some data along with the user ID on Firebase. However, I am encountering an error stating $fireDb is undefined, despite successfully creating the user without any additional information:

function createNewAccount (user) {
  const databaseRef = this.$fireDb.ref(`accounts/${user.uid}`)
  return databaseRef.set({
    displayName: 'Test Display Name', // using part of the email as a username
    email: 'My Test Email',
    image: 'Some Image' // providing a default profile image for all users
  })
}

export const actions = {

  /*
   * Creating a new user
   */
  createUser ({commit}, payload) {
    this.$fireAuth.createUserWithEmailAndPassword(payload.email, payload.password).then(function({user}) {
      commit('localStorage/setUser', { email: payload.email }, { root: true })
      createNewAccount(user)
    }).catch(function(error) {
      console.log('error registering' + error)
    });
  }
}

I'm currently investigating why this.$fireDb remains undefined. Despite following the documentation, it appears that something may be amiss in this aspect?

https://github.com/lupas/nuxt-fire#usage

Answer №1

If you're attempting to use .this outside of the store within your createNewAccount() function, there may be some limitations.

You can utilize this.$fireDb within your store, .vue files, and nuxt plugins, but it's not readily available outside of those contexts.

To resolve this issue, consider moving the function into a store action like below:

export const actions = {
  /*
   * Create a user
   */
  createUser({ commit, dispatch }, payload) {
    this.$fireAuth
      .createUserWithEmailAndPassword(payload.email, payload.password)
      .then(function({ user }) {
        commit('localStorage/setUser', { email: payload.email }, { root: true })
        dispatch('createNewAccount', true) // MODIFIED HERE
      })
      .catch(function(error) {
        console.log('error registering' + error)
      })
  },

  createNewAccount({ commit }, user) {
    const databaseRef = this.$fireDb.ref(`accounts/${user.uid}`)
    return databaseRef.set({
      displayName: 'Test Display Name', // assign part of the email as username
      email: 'My Test Email',
      image: 'Some Image' // set default profile image for users
    })
  }
}

Alternatively, run it anywhere in your app where the nuxt context is accessible through .this.

Hope this explanation helps :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js returns empty results when using the find() method in MongoDB

Within my node application, I have integrated MongoDB for data storage using Mongoose. Below is a snippet of my code: var client = new OAuthClient({"name":"default"}); client.user = req.user; client.username = req.body.username; c ...

Is the contact form confirmation message displaying too prominently?

I am currently troubleshooting two different forms on a website I'm developing, and I am unsure of the exact cause of the issue. Form 1: Form 2: When attempting to submit Form 1 without entering any information, an error message is displayed exactl ...

Instructions for creating a po file from a js file using poedit

Utilizing the Gettext.js library for localizing content created from a JS file has been my approach. The current challenge lies in the manual creation and writing of each po file. It is known that php files can be scanned for gettext strings using PoEdit ...

List of Nodes with five links

I'm encountering an issue when trying to reference the final node. The expected output is: Linked List with 5 nodes Node Value: Head Node / Next Node Value: Second Node / Last Node Value: null Node Value: Second Node / Next Node Value: Third N ...

Creating scalable controllers in ExpressJS

Recently diving into Node, I am venturing into the realm of creating an MVC app with ExpressJS. To mimic the structure of a well-known MVC example found on GitHub, I have organized my controllers into two main folders: main and system. My goal is to establ ...

I am having trouble setting an object in the state using React hooks

When assigning an initial value to a state as null, the setState method does not hold the value when assigned. Calling an API in useState returns an object which cannot be directly put into setState. const [userProfile, setProfile] = useState(null); cons ...

Exploring VUE and Firebase: Uncovering the Process of Retrieving User Profiles from Real-Time Database

After retrieving the user profile from the Realtime database, I noticed that when there are multiple accounts, it also fetches the profile of the second user. Below, you can see data from two users. However, my objective is to extract the details of the u ...

save choice in antd select in react js

In the process of developing a ReactJS project, I am utilizing the antd select component to display a list of companies. Upon selecting a company name, the users registered under that company will be shown. The attached video showcases the functionality fo ...

Different techniques for retrieving elements generated by ng-repeat from their containing parent

Let's keep it simple - imagine we have a directive called headSlides. This directive's template includes an image that is being repeated using ng-repeat: <img class="bg" ng-repeat="image in images" ng-src="{{image.src}}"> I need to access ...

What setting should I adjust in order to modify the color in question?

Looking to Customize Radar Chart Highlighted Line Colors https://i.sstatic.net/PqWc4.png I am currently working on a Radar Chart and I am trying to figure out which property needs to be edited in order to change the color of the highlighted lines. I have ...

"The issue of Django showing a 'select a valid choice' error when trying to populate a select field

I encountered a validation error while trying to create a form with an empty select field: area_sp = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control', 'id':'area_select'})) After populating the ...

What are the implications of using eval() to interpret function parameters?

I've recently utilized Hopscotch to create a interactive tour on my Website. To implement this, you need to create a JavaScript object as a parameter to trigger the startTour() function which will kick off the tour. For instance, in this case, the tou ...

The Angular method for retrieving the child's ID when it is clicked

As a newcomer to Angular 1.0 with a background in jQuery, I am facing the following scenario: Let's imagine we have the following HTML structure : <div id="filters"> <div id="filter1">Filter 1</div> <div id="filter2"> ...

I'm having trouble saving the session, what could be the issue?

Hey there, I've created a form where users can sign up. Once the user fills in all the details and clicks submit, an Ajax request sends the form data to the database. If this process happens without any errors, a hidden div containing payment buttons ...

Ensure the item chosen is displayed on a single line, not two

I've encountered an issue with my select menu. When I click on it, the options are displayed in a single line. However, upon selecting an item, it appears on two lines - one for the text and another for the icon. How can I ensure that the selection re ...

What is the best way to alternate $httpBackend when[method] declarations in unit tests to handle multiple requests?

When conducting my testing, I set up the model data and mock the response: beforeEach(function(){ var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/); $httpBackend.whenGET(re).respond({id:12345, usersOnline:5000}); }) ...

Running the JavaScript function prior to its interval being triggered

I'm in the process of developing a PHP dashboard page with various features, but there's one particular issue that bothers me, although it's not too major. The problem I'm facing is that I have a JavaScript function that fetches data a ...

What is the most efficient way to loop through a tree structure of interconnected objects and convert them into an array?

A database stores family members on a family tree. A function is designed to query all relatives of a user and compile their contact information and metadata into a list of unique entries, regardless of order. The issue arises when the function only retri ...

Troubleshooting HTTP requests in Angular JS when dealing with nested scopes

This particular question is derived from a previous answer found at this link. In my current scenario, I am attempting to initiate an http request where one of the data values that needs to be sent is represented in the view as {{selectedCountry.shippin ...

AngularJS Error: Attempting to Access Undefined Object - Jasmine Testing

Encountering an error while running Jasmine tests when trying to mock/spy on an API call in the tests. Below is the code snippet responsible for calling the API: UploadedReleasesController.$inject = ['$log', '$scope', '$filter&apo ...