Guide: Initiating an action in NuxtJs

I am attempting to trigger an action in my Vue component from my Vuex store.

Below is the content of my aliments.js file in the store:

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex, axios);

export const state = () => ({
  aliments: {},
})
export const mutations = () => ({
  SET_ALIMENTS(state, aliments) {
    state.aliments = aliments
  }
})
export const actions = () => ({
  async getListAliments(commit) {
    await Vue.axios.get(`http://localhost:3080/aliments`).then((response) => {
      console.log(response);
      commit('SET_ALIMENTS', response);
    }).catch(error => {
      throw new Error(`${error}`);
    })
  }

})
export const getters = () => ({
  aliments (state) {
    return state.aliments
  }
})

I intend to display a list of aliments in my Vue template using :

{{ this.$store.state.aliments }}

To call my action, I have the following script:

<script>
import { mapGetters, mapActions } from 'vuex'

export default {

  computed: {
    ...mapGetters(['loggedInUser', 'aliments']),
    ...mapActions(['getListAliments']),
    getListAliments() {
      return this.$state.aliments
    }
  }
}
</script>

However, I am having trouble identifying where I might be going wrong :/

Note: I have also attempted using an onclick method on a button with dispatch('aliments/getListAliments')... but it didn't yield the desired results...

Answer №1

One issue arises when you try to associate your actions within the "computed" segment of the component. It would be more appropriate to map them in the "methods" section instead!

Answer №2

Hey there, welcome to StackOverflow!

If you're looking for a quick solution to your query, you can call an action like this:

this.$store.dispatch('<NAME_OF_ACTION>', payload)

You can also use mapActions for a more concise syntax:

...mapActions(['getListAliments']), // and then call `this.getListAliments(payload)`

Alternatively, you can try this approach as well:

...mapActions({
  the_name_you_prefer: 'getListAliments' // and you call `this.the_name_you_prefer(payload)`
}), 

For getters, it follows a similar pattern. If you have defined ['loggedInUser', 'aliments'], you can simply access the getter like a computed value

<pre>{{ aliments }}</pre>

In cases where additional processing is required (such as filtering), you can do the following:

getListAliments() {
    return this.$store.getters['aliments']
}

However, I see that your store seems to be designed in a single comprehensive manner. Since you are using Nuxt, consider utilizing the module store feature for better organization.

As your project scales, instead of storing everything in a single file like ~/store/index.js, you could create separate stores. Taking inspiration from your example, you might have a file named:

~/store/food.js with the following content:

(Content of food.js store module goes here...)

Don't forget that if you are using Nuxt's serverMiddleware, adjust the API request URLs accordingly to something like axios.get('/aliments')....

To access different stores, prefix the filename when calling actions like so:

...mapActions(['food/getListAliments'])
// or
...mapActions({ getListAliments: 'food/getListAliments' })
// or
this.$store.commit('food/getListAliments', payload)

Consider renaming your actions and getters for clarity:

  • Rename getListAliments to fetchAliments to better reflect its purpose.

  • Rename aliments to getAllAliments since it returns a list.

Enjoy working with Nuxt! It's a fantastic tool, and you can always turn to the vibrant community on Discord for support.


EDIT

Also, keep in mind that actions belong in the methods section:

...
export default {
    methods: {
        ...mapActions(['getListAliments']),
    },
    created() {
        this.getListAliments()
    }
}

In your Store action, ensure you destructure the property passed correctly:

async getListAliments({ commit }) { ... }

Use curly braces for proper deconstruction:

async getListAliments(context) { 
   ...
   context.commit(...)
}

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

Retrieve a div element using two specific data attributes, while excluding certain other data attributes

Here are some examples of divs: <div id="1" data-effect-in="swing" data-effect-out="bounce"></div> <div id="2" data-effect-in="swing"></div> <div id="3" data-effect-out="swing"></div> <div id="4" data-effect-out data ...

Using Ajax to submit two forms by clicking a submit button

Explanation : In this particular scenario, I am facing a challenge where I need to trigger another Ajax function upon successful data retrieval, but unfortunately, I am encountering some unknown obstacles. Code: ---HTML Form : <form accept-charset=" ...

Generate a folder structure based on the Delta data provided by the Dropbox API utilizing the file paths

I came across a query on how to convert a file path into a treeview, and I'm uncertain about achieving the desired outcome using JavaScript: My goal is to transform an array of paths into a JSON tree structure: var paths = [ "/org/openbm ...

Preventing redirection post-AJAX call using jQuery

Currently, I am attempting to implement a basic form submission using AJAX to send data to submit.php for database storage. However, upon submission, the page redirects to submit.php instead of staying on the current page. How can I make it submit without ...

My JavaScript code is being executed before Chrome Auto-fill

I have successfully created form input elements in Chrome that display a floating label when focused. However, I am encountering an issue when the browser autofills the username and password fields with yellow prefilled text. The JavaScript for the float ...

When validated, the Yup.date() function seamlessly converts a date into a string without including the timezone

Currently, I am integrating Yup with react-hook-form and have defined the following schema in Yup: const validationSchema = Yup.object({ installation: Yup.string().nullable().required("Required"), from_date: Yup.date() .max(new Date(), "Can ...

Redux: The action was effectively triggered, but the state remained unformed

I'm currently working on a project to familiarize myself with Redux. I am using the Redux DevTools to monitor my two states: lists and todos. However, I am running into an issue where only todos are being displayed, despite trying various troubleshoot ...

What is the best way to implement jQuery after new elements have been added to the DOM?

I'm currently working on a Sentence Generator project. The program is designed to take a list of words and retrieve sentences from sentence.yourdictionary.com based on those words. The first sentence fetched from the website is displayed using the cod ...

Encountered an issue while trying to extract data from state - property of null cannot

I'm facing an issue trying to show a navigation item only when a specific flag is true. The problem arises when I attempt to extract data from it, as it returns undefined. Below is the code snippet I have created for this scenario: let navigate = useN ...

Looking to incorporate React Canary in raw HTML? Or perhaps interested in adding react-dom/client into your project?

Due to certain undisclosed reasons, I am developing a React application without the use of bundlers like webpack. Instead, I simply include React and ReactDOM using <script> tags in my index.html, fetching them from a CDN: https://cdnjs.cloudflare.co ...

Breaking down object properties to 'this' using destructuring in javascript

I would like to set the pagination result from response.data to Vue data. The standard approach would be: this.resultData = response.data.results this.totalResults = response.data.total this.perPageResults = response.data.per_page However, ...

Angular facing problems with tracking comment counts in Disqus

After successfully setting up the Disqus comments system on my Angular website following the guide at , everything was working fine. However, when attempting to add the Disqus comment count system to my homepage using the code provided at , I encountered a ...

Is it possible for a popup to appear without any user interaction

Do you ever wonder how certain websites are able to trigger pop-ups without being blocked by Chrome's pop-up blocker? I had always thought that pop-up blockers only allowed window.open if it was initiated by a user action. However, the situation seem ...

`Month filter functionality optimized`

I have a flirty plugin installed on my website and it's working great except for one thing: I'd like the month category to be filtered in chronological order instead of alphabetically. Is there a way to achieve this? In simpler terms, how can I ...

Is it possible to view the object sent from AJAX to PHP in PHP using a debugger?

I'm facing an issue where I am making an AJAX call to a PHP file, sending a JSON object as a parameter from JavaScript. The PHP file is supposed to perform some logic with the object and return it using json_encode('whatever');. However, the ...

Steps to reinitialize the error code after removal from the roster

Currently, I am working on creating a series of textboxes and dropdown menus using jQuery. So far, the add function is functioning smoothly without any glitches. However, my issue lies within the delete function. It works well when deleting sequentially, ...

What is the method for identifying modules that rely on a specific module?

Is it possible to view all dependencies modules of a specific module, similar to this: npm-remote-ls <module-name> But how can we see the modules that depend on a particular module? Any help would be appreciated. Thank you. ...

Transforming data structures into arrays using Javascript

Could someone help me with converting the following code snippet? const words = {told: 64, mistake: 11, thought: 16, bad: 17} I need it to be transformed into: const words = [ {text: 'told', value: ...

The Jquery AjaxStop event fails to trigger, but AjaxStart works perfectly

While I was working with APIs, I encountered a roadblock. I have a Jquery function that retrieves data from an API. To prevent a "reposition" effect, I need the function to wait until all calls are made before triggering another function to place all the ...

How can JSON data objects be transmitted to the HTML side?

I created a JSON object using Node JS functions, and now I'm looking to transfer this data to the HTML side in order to generate a table with it. However, I'm encountering difficulties sending the JSON object over because of my limited experience ...