When trying to sign up a user in Nuxt, an error occurs stating "Cannot read property 'then' of undefined."

I've been encountering an issue while trying to sign up or log in as a user from my Nuxt app to an API that is functioning perfectly. The error message

Cannot read property 'then' of undefined
keeps popping up, and I can't figure out the reason behind this error. Another error message that I come across is
unknown action type: authenticateUser
.

Previously, I successfully made a post request from the signup page. However, since I am now attempting to store some data, I decided to move the axios request to the store.

Below is the code snippet for reference:

On the signup page, when clicking on the signup button, it triggers the createAccount method.

data() {
    return {
      isSignup: true,
      form: {
        email: null,
        fullname: null,
        password: null
      }
    }
},
methods: {
    createAccount() {
      this.$store.dispatch("authenticateUser", {
        isSignup: this.isSignup,
        form: this.form
      })
      .then(() => {
        this.$router.push('/loginsuccess')
      })
      .catch(e => console.log(e))
    }
  }

In my store/profile.js file, which is configured as a store module, I have specified the mutations and actions:

export const mutations = {
    setToken(state, token) {
        state.token = token
    },
    logIn(state) {
        state.loggedin = true
    }
}

export const actions = {
    async authenticateUser(vuexContext, authData) {
        let authUrl = 'https://lookaam.herokuapp.com/signup/'
        if (authdata.isLogin) {
            authUrl = 'https://lookaam.herokuapp.com/login/'
        }

        return await this.$axios
        .$post(authUrl, authData.form)
        .then(result => {
            const token = result.data.token
            vuexContext.commit('setToken', token)
        })
        .catch(e => console.log(e))
    },
}

In my nuxt.config.js file, I have the following setup:

  modules: [
    '@nuxtjs/axios',
  ],

  axios: {
    baseURL: process.env.BASE_URL,
    Credentials: false 
  },

Upon clicking the signup button, I immediately see both

unknown action type: authenticateUser
and
Cannot read property 'then' of undefined
errors on the console, indicating a failure in communication with the API.

I'm puzzled by this issue and would appreciate any insights into resolving it.

Answer №1

createAccount() is triggering the action without specifying the correct namespace ("profile" for store/profile.js). When this.$store.dispatch() is used with an unknown action, it returns undefined, resulting in the error you encountered.

To resolve this issue, ensure to include the profile namespace in the dispatch:

this.$store.dispatch("profile/authenticateUser").then(...)
                         👆

It's also important to note that the $ shortcuts will give you the actual response data instead of the axios.Response instance. In the case of your authenticateUser action, using this.$axios.$post() will directly provide you with the token:

export const actions = {
  async authenticateUser(vuexContext, authData) {
    //...
    return await this.$axios
      .$post(authUrl, authData.form)
              👇
      .then(token => {
         vuexContext.commit('setToken', token)
      })
      .catch(e => console.log(e))
  },
}

Check out the demo here

Answer №2

It is my understanding that chaining multiple then methods may not produce the desired outcome. However, you can achieve the behavior you want by monitoring the loggedin state and then redirecting to the URL if it is true:

data() {
    return {
      isSignup: true,
      form: {
        email: null,
        fullname: null,
        password: null
      }
    }
},
computed:{
  isLoggedn(){
    return this.$store.state.loggedin;
  }
},
watch:{
  isLoggedin(newVal){
   if(newVal){
       this.$router.push('/loginsuccess')
    }
  }
},
methods: {
    createAccount() {
      this.$store.dispatch("authenticateUser", {
        isSignup: this.isSignup,
        form: this.form
      })
    }
  }

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

Error: The server is unable to process the POST request to /api

Currently following a tutorial on YouTube: https://www.youtube.com/watch?v=4ECVE6TXKLQ&list=PLI-gk4ISRzCPlJjCz3yuAhL8vnmK6KWr7&index=11 After setting up a server listening on port 8080 and connecting to MongoDB Atlas successfully, the next step ...

Why is the startsWith function not returning the expected result in my code? What could be causing this issue?

I have a code snippet that sorts a list based on user input, but it fails if the user's input contains spaces. How can I modify the code to handle inputs with spaces without removing the spaces between characters? For example, if the user input is &ap ...

Converting Datepicker selection to a string format in AngularJS

Can anyone help me figure out how to convert a datepicker value into a string that can be passed as a parameter to a get method without causing an error? <div ng-app="getserviceApp" ng-controller="getserviceCtrl"> <button ng-click="Func ...

Check the box by clicking on the label to activate it [Vue.js]

While browsing online, I came across a fantastic tutorial on creating a toggle component on YouTube. https://www.youtube.com/watch?v=J0hp2NF5OzU&ab_channel=LaurentPerrier At the 23rd second mark, the instructor demonstrates that clicking on the label ...

Accessing data from an API in an AngularJS dropdown menu

After retrieving JSON data from an API, I store it in $scope.industry. $scope.industry = []; $http.get('/industrygroup?languageid=1') .then(function (result) { $scope.industry = result.data; }); The JSON data st ...

Presenting information on an HTML webpage using the slidetoogle feature

< script > $(document).ready(function() { $("#flip").click(function() { $("#panel").slideToggle("fast"); }); }); < /script> When a button in a particular panel is clicked, I aim to display the details of that specific tuple ...

Dynamic color updates for Angular list items on click

Utilizing angularjs, I have two lists. When the first one is clicked, the value will be pushed into another scope and bound to the second list. Now, my goal is to change the color of the values moved from the first list to the second list in list1. Check ...

A dropdown menu generated from a Google Sheet script that allows for the input of custom text alongside predefined

Currently, I am working on creating a dropdown list that not only allows me to select items but also input free text. The code below enables me to choose an item from a selected range in Google Sheets. However, I am looking for a way to incorporate the f ...

Prevent caching of dynamically generated HTML while still caching static resources such as images, JavaScript, and CSS files in

When it comes to PHP development, many developers opt to include the no-cache header at the beginning of their PHP pages - a practice I also follow for obvious reasons. Since PHP-generated content is typically dynamic, allowing browsers to cache this infor ...

The video does not begin playing automatically after utilizing react-snap

I included a background video in my react app that auto-plays upon page load and functions perfectly. Here is the JSX code I used: <video autoPlay loop style={{ backgroundImage: `url(${topVideoImage})`, }} muted playsInl ...

Error: The function Users.create is undefined

After my code was initially running smoothly, I decided to add some new functions for login which unfortunately caused it to break. Even after removing the added code, the error message "create function of the user service is not a function" persists. Desp ...

JavaScript scripts are not functioning properly in a partial view following a refresh

Issue: The partial view contains JavaScript scripts that work when first loaded, but stop working after being loaded a second time. Description: I have a partial view reloading on value change in a select box (which calls this function). @(Html .DevE ...

Choose from the Angular enum options

I am working with an enum called LogLevel that looks like this: export enum LogLevel { DEBUG = 'DEBUG', INFO = 'INFO', WARNING = 'WARNING', ERROR = 'ERROR' } My goal is to create a dropdown select el ...

GraphQL component properties

Working on a basic web application using React and GatsbyJS, with content management handled by NetlifyCMS. Utilizing gatsby-transformer-remark to load image paths for display through gatsby-transformer-sharp. Created an Image component that takes in the ...

When utilizing Vuetify's cards in a Vue component and rendering multiple items with a v-for loop, the data and methods may unexpectedly vanish on

Within my Vue component, I am rendering a collection of Vuetify cards: <restaurant-item v-for="card in userRestaurantCards" :key="card['.key']" :card="card" > </restaurant-item> These cards showcase information ...

Utilizing reference memory to enable communication between two controllers

Within my Angular application, I have implemented a service to facilitate communication between 2 controllers and allow them to share the input variable from the search box. I am using kickSearch.box to reference memory...obj.property. However, there seem ...

utilize text offsets to insert tags within strings

I've been facing challenges with using JavaScript string methods and regular expressions. It seems like I might be missing something obvious here. Please forgive me if I'm repeating the question asked by tofutim in more detail, which can be found ...

What is the best way to dynamically adjust the size of a grid of divs to perfectly fit within the boundaries of a container div without surpassing them?

Currently, I am working on a project for "The Odin Project" that involves creating a web page similar to an etch-a-sketch. I have made some progress, but I am facing a challenge with dynamically resizing a grid of divs. The issue lies with the container d ...

Limiting the character count in a textarea can be achieved by implementing the 'jQuery InlineEdit' feature

Currently, I am utilizing the jquery.inlineedit.js plugin for inline editing, and one of my requirements is to limit the maximum length of text within the textarea. I have attempted to use other popular jQuery scripts for this purpose, but unfortunately, I ...

Trouble retrieving data (React-redux)

Greetings! I am currently working on a project involving the Spotify API and attempting to retrieve new releases. While the data is successfully passed down to the reducer, I encounter an issue when calling the fetch action in my App component. When I try ...