Encountering the error message "Unable to access properties of undefined (specifically 'commit') in NUXT"

I'm encountering a roadblock as a newcomer to Vue. My goal is to capture user input data from a form and transfer it to a Vuex store. Once in the Vuex store, an action will trigger (fetching from an API) and I aim to retrieve that data back into my app and components.

<template>
  <div>
    <h1>APP NAME</h1>
    <form action="submit" @submit.prevent="sendCityName()">
      <label for="query"></label>
      <input 
      type="text"
      id="query"
      v-model="cityName"
    >
      <button type="submit">Submit</button>
    </form>
    <h3>{{ lat }}</h3>
  </div>

</template>

<script>
import { mapState } from 'vuex'
export default {
  data() {
    return {
      cityName: ''
    }
  },
  computed: {
    coordinates () {
      return this.$store.state.lat
    }

  },
  methods: {
    sendCityName() {
      this.$store.commit('fetchCity', this.cityName)
    }
  },
}
</script>

Index.vue is where I am facing the issue of "Cannot read properties of undefined (reading 'commit')".
I have also included my store.js file in which I intend to utilize the lat and lon values throughout my application.

export const state = () => ({
    lat: '',
    lon: ''
  })
  
export const mutations = {
    SET_LAT(state, payload){
      state.lat = payload
    },
    SET_LON(state, payload){
      state.lon = payload
    }
  }
  
export const actions = {
    async fetchCity({ commit }, cityName) {
      // make request
      axios.get(
        `https://api.openweathermap.org/geo/1.0/direct`, {
          params: {
            appid: "xxxxxxx",
            q: cityName,
          }
        }).then((response) => {
            commit('SET_LAT', response.data[0].lat);
            commit('SET_LON', response.data[0].lng);
        }); 
    },
  };

Upon clicking the submit button, the error "Cannot read properties of undefined (reading 'commit')" occurs.

Answer №1

Check out my active repository for the solutions mentioned below.


Your code needs attention in 3 areas:

  • Remove vuex from your package.json, then re-run yarn. Remember, Nuxt already includes Vuex by default as explained in the official documentation.
  • All files within the store directory will automatically be namespaced for you. With a file named store.js, use this syntax:
async sendCityName() {
  await this.$store.dispatch('store/fetchCity', this.cityName) // 👈🏻 store prefix
}
  • If you're using the axios module, make sure to include the following in your action using modern async/await syntax:
async fetchCity({ commit }, cityName) {
  const response = await this.$axios.get(
    `https://api.openweathermap.org/geo/1.0/direct`, {
    params: {
      appid: "3d91ba5b3c11d13158a2726aab902a0b",
      q: cityName,
    }
  })
  commit('SET_LAT', response.data[0].lat)
  commit('SET_LON', response.data[0].lng)
}

The browser console is showing some errors that need to be addressed.

https://i.stack.imgur.com/QK6RM.jpg

I suggest checking out ESlint + Prettier setup to ensure your code stays error-free and well-formatted.

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

Bypassing redirection in Nuxt for seamless login experience

I've been exploring ways to implement authentication on my Nuxt app, but I'm struggling to find a tutorial that doesn't rely on redirecting to public or private paths. For example: if (user.isLoggedIn()) { redirect('/dashboard&apo ...

Display tooltip information based on dynamic content

Can the q-tooltip text be loaded dynamically? Which property should be used for this purpose? In my scenario, which property should replace :value (please note that this is just a demonstration and not an actual property of q-tooltip)? <q-item-sectio ...

How can Vue detect modifications made in the edited field?

I am facing an issue with tracking changes in a specific object. Here is the structure of the object: users: { email: '', password: '' } My goal is to detect any edits made to the keys within the users object and store the key ...

The parameters in VueJS are malfunctioning on this webpage

I created my vue in an external file and included it at the bottom of my webpage, but I am encountering issues with its functionality. One specific problem arises when using v-model, resulting in a template error displayed on the page: Error compiling t ...

Adding properties with strings as identifiers to classes in TypeScript: A step-by-step guide

I am working with a list of string values that represent the identifiers of fields I need to add to a class. For instance: Consider the following string array: let stringArr = ['player1score', 'player2score', 'player3score' ...

"Discover the best way to retrieve data within a Vuex store during the mounted or created lifecycle functions

After storing data in Vuex, I encountered an issue when trying to access my Vuex store after changing routes (components). When inside the mounted function, it shows me an error and fails to return the data. How can I resolve this? I am aware that using a ...

Storing image links in a MongoDB database without converting the images to base64 allows for easier management and faster retrieval of the images. Additionally, by implementing a way

Is there a way to store image links in MongoDB without converting images to base64 and easily add new pictures to the database upon deployment? I've tried using the multer package, but newly uploaded images are not displaying on deployment. Additional ...

Troubleshooting: Why does getElementById return undefined in Vue's mounted hook?

I'm facing an issue when trying to access the DOM using Vue3 mounted hook. Interestingly, I've found that utilizing the getElementById or getElementByClassName functions within the mounted hook results in undefined values, whereas using the quer ...

The function 'replace' is not supported by Object in Internet Explorer 11

I'm currently facing an issue while trying to get my Vuejs application to function properly on IE11. One of the node modules (vue-directive-tooltip) is causing an error specifically on IE11: "Object doesn't support property or method 'repla ...

The compatibility between V-model and TinyMCE is unreliable

I've been working on integrating Vuejs and TinyMCE, using the @tinymce/tinymce-vue package for the Vue integration. I followed all the instructions and everything seems to be functioning properly - I can write, insert images... everything except for t ...

Modifying the Vue page background directly from a page: a step-by-step guide

UPDATE: I recently discovered that I need to modify the body background-color, but I am unsure of how to accomplish this from within the style of this page based on the wrapper's class. The class is determined by the data values. I aim to change the ...

Using Vue.js, you can set a method to return data directly to

Having just begun my journey with Vue, I find myself in a bit of a predicament. As part of my learning process, I am developing an app for tracking episodes in TV series. The initial step involves searching for series and adding them to a database. When co ...

Troubleshooting Vue Single File Components Displaying Missing Styles

I'm currently attempting to incorporate styles into a vuejs single file component. I've successfully achieved this in a node app previously, but now I am working with a python/flask backend (not that it should make a difference). The Vue componen ...

Is there a way to turn off linting while utilizing vue-cli serve?

I am currently running my project using vue-cli by executing the following command: vue-cli-service serve --open Is there a way to stop all linting? It seems like it's re-linting every time I save, and it significantly slows down the process of ma ...

Tips for utilizing the /foo-:bar pathway in Nuxt.js?

I am trying to utilize the router /foo-:bar in Nuxt. Do you have any suggestions on how I could make this work? I attempted using pages/foo-_bar.vue but it did not yield the desired results. ...

Guide to validating a form using ref in Vue Composition API

Incorporating the Options API, I implemented form validation in this manner: template: <v-form ref="form" v-model="valid" lazy-validation @submit.prevent> ... script: methods: { validate() { this.$refs.form.validate(); ...

Monitoring Vue for ongoing HTTP requests

Upon mounting a component, it initiates 4 HTTP requests (using Axios) to fetch the necessary data. Is there a method to monitor for any outstanding HTTP requests? To simplify: Are there any pending HTTP requests? yes -> Loading=true no -> Loading ...

What could be preventing my component from importing properly in App.vue?

I am attempting to display a pulse loader while the page is loading. However, I encountered two errors in the code below. App.vue <template> <div id="app"> <div id="nav"> <router-link to='/'><div v-if="$ro ...

While making a promise, an error occurred: TypeError - Unable to access the property '0' of null

I encountered an issue when trying to assign data from a function. The error appears in the console ((in promise) TypeError: Cannot read property '0'), but the data still shows on my application. Here is the code: <template> ...

What is the best way to use arrow functions in VueJS?

Here is how my method in vue currently looks: methods: { setDate: async function () { console.log(this.modal) } } I want to convert it into an arrow function. I tried the following approach: methods: { setDate: async () => { ...