What is the best way to display data from the Nuxt.js store?

I am new to Nuxt JS and following a tutorial on the Nuxt website. I created a store in store/index.js.

export const state = () => ({
  mountain: [],
})

export const mutations = {
  addMountain(state, mountain) {
    state.mountain.push(mountain)
  },
}

export const actions = {
  async fetchMountain() {
    const mountain = await fetch("https://api.nuxtjs.dev/mountains").then(
      (res) => res.json()
    );
    // this.mountain = mountain
  }
}

After that, I created a page in pages/index.js.

<template>
  <div>
    <h1>Nuxt Mountains</h1>
    <ul>
      <li v-for="mount of mountain">{{ mount.title }}</li>
    </ul>
    <button @click="$fetch">Refresh</button>
  </div>
</template>

<script>
import $store from "~/store";

export default {
  fetch() {
    return $store.state.mountain;
  },
};
</script>

However, when I run the page, I don't see anything displayed. Can someone help me with this issue?

https://i.sstatic.net/Ua3Mt.png

Answer №1

Follow these steps to replicate the provided example.

/pages/index.vue

<template>
  <div>
    <h1>Nuxt Mountains</h1>
    <p v-show="$fetchState.pending">Loading mountains...</p>

    <ul v-show="!$fetchState.pending">
      <li v-for="mountain of mountains" :key="mountain.slug">
        {{ mountain.title }}
      </li>
    </ul>

    <hr />
    <button @click="$fetch">Refresh</button>
  </div>
</template>

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

export default {
  async fetch() {
    await this.fetchMountains()
  },
  computed: {
    ...mapState(['mountains']),
  },
  methods: {
    ...mapActions(['fetchMountains']),
  },
}
</script>

Key points to note:

  • mapState and mapActions are not compulsory here; you could access them via $store.dispatch, etc., directly but using them is considered cleaner and a good practice
  • Ensure you include the :key attribute in the v-for; it is mandatory
  • Prefer utilizing async/await consistently instead of mixing with .then

/store/index.js

export const state = () => ({
  mountains: [],
})

export const mutations = {
  SET_MOUNTAINS(state, mountains) {
    state.mountains = mountains
  },
}

export const actions = {
  async fetchMountains({ commit }) {
    const response = await fetch('https://api.nuxtjs.dev/mountains')
    const mountains = await response.json()
    commit('SET_MOUNTAINS', mountains)
  },
}

Key aspects to consider:

  • Using UPPER_SNAKE_CASE for mutation names is a recommended convention
  • Consistently applying the async + await pattern
  • Naming the data as mountains (plural) makes more sense since there are multiple items
  • Calling the mutation after fetching data from an API within the action method aligns with standard practices in Nuxt2

Answer №2

The store object is already available in your context, so there's no need to import it. Here's an example of how to use it:

 computed: {
     mountain () {
           return this.$store.state.mountain;
     }
  }

ps. Why put this inside the computed property? Because we want to avoid unnecessary rerendering of the component whenever a module update occurs. Only changes to the data being accessed should trigger a rerender.

However, using modules would be a better practice.


To understand this concept better, it's important to know that Nuxt automatically imports all files within the store folder.

Every file created within the store folder will function as a new module in the Vuex store. For example, if you create a file named todo.js in the store folder, you can access it throughout the project like this:

 computed: {
     mountain () {
           return this.$store.state.todo.mountain;
     }
  }

I recommend exploring this further here: https://nuxtjs.org/docs/directory-structure/store/

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

Delete Entries in MongoDB Collection According to Unique User Pairs

I have a collection of messages stored in MongoDB and I need to keep only the latest 500 records for each pair of users. Users are identified by their sentBy and sentTo attributes. /* 1 */ { "_id" : ObjectId("5f1c1b00c62e9b9aafbe1d6c&quo ...

Cloned element does not trigger on click event

When using jQuery 1.10, I encountered an issue where cloning a div containing a button with a click event defined did not retain the click event on the cloned div. I have come across similar questions multiple times, and existing solutions advise using cl ...

Is it possible to switch from a dropdown menu to radio buttons?

I am looking to change the dropdown menu in my search section into radio buttons. Currently, when I select something from the dropdown menu, the search fields are altered. Here is the code for the dropdown menu: <select id="qs_category" name="qs_catego ...

Set up npm and package at the main directory of a web application

Currently, I am in the process of developing a web application using node.js. Within my project structure, I have segregated the front-end code into a 'client' folder and all back-end logic into a 'server' folder. My question revolves a ...

I am experiencing an issue with the checkbox in my React app where the state is not updating after it has been

I am currently building a todo app using React, but I'm encountering an issue where nothing happens when I click the checkbox. I've provided my code below: App.js import './App.css'; import React from 'react' import TodoItem ...

Utilizing a shared service for multiple JSON datasets in AngularJS: A beginner's guide

After successfully creating a service that retrieves data from a local JSON file and uses it in a controller to display it in the browser, everything seems to be working well. Here is the code snippet: JavaScript Code: var myApp = angular.module("myApp", ...

Obtain information from express middleware

I am currently working on a project using node.js. As part of my application, I have developed a middleware function that is triggered whenever a GET request is made. This occurs when someone visits the home page, profile page, or any other page within my ...

Iterating through a list using curly braces in a vue for loop

I encountered a scenario where I need to iterate through items without generating any HTML. My anticipation is for the code to resemble something like this: <table id="detailTable"> <tr> <th class='editRow' ...

Tips for generating a <div> element with multiple children using a loop

section, I have configured a div element with a class named div class = "postWindow". When it comes to the HTML code, here is an example: <div class = "postWindow"> <div class = "userName">Initial Name</div> <div class = "p ...

Retrieving a component's property within its event handler in React

In the React component, there is a need to create multiple instances with different key values passed as arguments to the onClick event handler. However, the issue arises when using a variable such as 'value' in a for loop, as it ends up taking t ...

Experiencing an issue of receiving an undefined value while attempting to retrieve a value from an input box

HTML: <input value='Rename' type='button' onclick='RenameGlobalPhase({$row['id']});' <span id='renameGlobalPhase{$row['id']}'>" . $row['phase'] . "</span> Below you wil ...

Maintain form activity post submission using jQuery's addClass and removeClass methods

There is a button on my website that, when clicked, reveals a form. The code I am using for this functionality is: $('#theform').addClass('hidden') $('#theform').removeClass('hidden'); <div id="theform" c ...

Launch the Image-Infused Modal

I am completely new to the world of Ionic development. Currently, I am working on a simple Ionic application that comprises a list of users with their respective usernames and images stored in an array. Typescript: users = [ { "name": "First ...

What is the best way to calculate the variance between the most recent and previous data points in an array in the span of an hour using JavaScript

Here is an array of objects I am working with: 0: {time: '2021-12-02T23:53:54.062Z', value: 558316} 1: {time: '2021-12-03T00:53:53.959Z', value: 558452} 2: {time: '2021-12-03T01:53:53.934Z', value: 558588} 3: {time: '2021 ...

The Vue3 counterpart of vNode.computedInstance

I'm currently in the process of upgrading my app from Vue2 to Vue3, but I've hit a roadblock when it comes to dealing with forms. For my form elements, such as FormInput, FormTextArea, and FormCheckbox, I have been using Single File Components ( ...

Problem with VeeValidate's Confirmed rule not being applied correctly in ValidationProvider

I am encountering an issue while trying to apply vee-validate rules on the Validation Provider for password and confirm password fields. Usually, v-validate works fine when adding rules to a textbox. However, in my case, I need to utilize Validation Provid ...

I am having trouble retrieving images from the backend API. Can someone assist me in resolving this issue?

I am facing an issue while trying to upload an image along with its details. I am able to retrieve all the information but the image is not displaying in the browser. My backend API is built using PHP Laravel and the images are stored in the Storage/app/ap ...

AngularJs Controller with explicit inline annotation

I usually inject dependencies using inline annotations like this angular.module('app') .controller('SampleController',['$scope','ngDependacy',sampleController]); function sampleController($scope,ngDependacy) { ...

Do not continue submitting if the innerHTML matches the specified value

I am currently working on a web page that verifies if an email entered by the user is available in the database. If it is, I need to prevent the form from being submitted. To achieve this, I have implemented Ajax for real-time checking of the email and di ...

How to access elements in every document fragment

I am facing an issue with a page that contains multiple document fragments. I need to retrieve all elements from the entire page that match a specific selector, like so. document.querySelectorAll('iframe') However, this does not return elements ...