Leverage the power of Vuex within your Nuxt application

I successfully obtained and displayed data using Nuxt's Fetch API, but now I'm looking to transition to using Vuex instead.

store/index.js:

import Axios from 'axios'

export const getters = {
  isAuthenticated: (state) => {
    return state.auth.loggedIn
  },

  loggedInUser: (state) => {
    return state.auth.user
  }
}
export const state = () => ({
  videos: []
})

export const mutations = {
  storeVideos: (state, videos) => {
    state.videos = videos
  }
}

export const actions = {
  async getVideos ({ commit }) {
    const res = await Axios.get(`https://api.themoviedb.org/3/movie/popular?api_key=${process.env.API_SECRET}&page=${this.currentPage}`)
    commit('storeVideos', res.data)
  }
}

pages/test.vue:

    <template>
          <Moviecards
            v-for="(movie, index) in $store.state.videos"
            :key="index"
            :movie="movie"
            :data-index="index"
          />
    </template>
    
    <script>
...
      fetch ({ store }) {
        store.commit('storeVideos')
      },
      data () {
        return {
          prevpage: null,
          nextpage: null,
          currentPage: 1,
          pageNumbers: [],
          totalPages: 0,
          popularmovies: []
        }
      },
      watch: {
    
      },
      methods: {
        next () {
          this.currentPage += 1
        }
      }
    }
...

Upon inspection using Vue Dev Tools, the array is showing empty.

Answer №1

When using fetch(), make sure you are dispatching the getVideos action instead of committing storeVideos without any arguments. Committing without an argument will result in store.state.videos being set to undefined:

export default {
  fetch({ store }) {
    // Incorrect:
    store.commit('storeVideos')

    // Correct:
    store.dispatch('getVideos')
  }
}

Furthermore, ensure that your action is correctly structured to utilize the Vuex context argument. You should destructure commit from the context:

export const actions = {
  // Incorrect:
  async getVideos (commit) {}  // Fix: 1st arg should be context

  // Correct:
  async getVideos ({ 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

Is there a way to asynchronously load image src URLs in Vue.js?

Why is the image URL printing in console but not rendering to src attribute? Is there a way to achieve this using async and await in Vue.js? <div v-for="(data, key) in imgURL" :key="key"> <img :src= "fetchImage(data)" /> </div> The i ...

Get all instances of a particular attribute value within an interface

In my TypeScript code, I have defined an interface and two constants: interface Foo { readonly name: string; }; const FOO_1: Foo = { name: 'zing' }; const FOO_2: Foo = { name: 'baz' }; Is there a way to find all instances ...

Unveiling the Power of AngularJS for Parsing JSON Data

A list of images is being generated in a table-like structure using the code snippet below. Each image represents a cell in this table, with its ID specifying its row and column position. <ul> <li class="row"> <ul> & ...

Retrieving data using a class in an AJAX form submission

I am attempting to use AJAX to submit an HTML form. Here is my HTML: <form class="lyrics"> <input type="text" value="" id="song" name="song"> <button type="submit" class="btn btn-info lirik">lyrics</button> </form> ...

defiant underscore refusing to function

I'm currently working on a text editor, but I'm facing an issue with the remove underline functionality that doesn't seem to be working as expected. For reference, you can check out a working code example here: jsfiddle Below is the part of ...

Ajax implementation for handling URL action parameters

I am currently facing challenges in passing data from a view to a controller using parameters. My goal is to pass these parameters when I select a row from a table and click on a button that triggers the ShowTasks() function. Here is the C# controller cod ...

Transferring data between functions within the same controller in AngularJS

I have implemented two functions to handle the timing of a process, one for starting and one for stopping. Here is the code snippet: $scope.start = function(data) { $scope.time = { id: '', mainId: data.id, start: &ap ...

Having an issue with the 'scroll' event not being disabled in jQuery

Currently, we are encountering an issue with the implementation of a simple hiding menu when scrolling and showing it back once the user stops scrolling. The method .on('scroll') works as expected, but .off('scroll') is not functioning ...

Telerik Nested perspective

Here is the code snippet that I am currently working on, which involves a nested grid from Telerik: I've encountered an issue with using JavaScript to locate and interact with controls named "PreviousDate" and "DateofBirth". <%@ Page Language="c# ...

Checking for the Existence of a Class Element within a String using JavaScript

Within my web project, there is a scenario where if a user has been logged out in one browser tab, they will automatically be redirected to the login page in any other browser tab after interacting with that page (such as clicking on a link). However, this ...

Guide on integrating a JavaScript control (JavaScript package) obtained from GitHub into my asp.net application

Hello everyone, I am a newcomer to GitHub and have some basic questions to ask. Recently, I downloaded the package from https://github.com/jspreadsheet/ce in .zip format for using in my asp.net web application. However, I am not sure how to incorporate the ...

Setting up a Node.js project in your local environment and making it

I need help installing my custom project globally so I can access it from anywhere in my computer using the command line. However, I've been struggling to make it work. I attempted the following command: npm install -g . and some others that I can&ap ...

Navigate through pages using scrollspy without losing your position when returning

Hey all you web geeks out there, I could really use your help solving a little issue. I've been working with Bootstrap to build a website that utilizes scrollspy for navigating different sections of the page using the navbar. The only way I could sto ...

Refreshing the Vuejs form is necessary for the router.push function to properly execute

Hey there! I've been working on a website that allows users to submit entries using a Laravel/Vuejs application. However, I've run into an issue where after filling out the form and submitting it, the loader gets stuck and the router.push doesn&a ...

What is the best way to showcase several components using VueJS?

I've been working on my todo list with vue.js and I want to spice it up by adding some images every 4th list item. My idea is to use v-html along with an array that contains elements binding text and images. What do you think? For example: var arr = ...

The Jquery confirmation dialogue does not seem to be functioning properly within the Content Place Holder

I've encountered an issue with a JQUERY Confirm dialogue where it works perfectly fine until I place it on a page that is within a masterpage. The confirm alert pops up for a split second and disappears. window.onload = function() { $("#ehi").cli ...

Tips for invoking the href function in jwplayer with individual arguments

I need assistance with configuring jwplayer to load a list of href links one by one. Each href link includes a function that needs to be triggered automatically with specific parameters passed to JavaScript. Below is the code snippet I am currently worki ...

Is it detrimental to my search engine ranking if I utilize CSS display:none?

Imagine having valuable content that is initially hidden with CSS, and then using javascript to reveal it only when the user clicks on certain links. Even users without javascript enabled can access this content by following the links to a new page where i ...

Optimizing Nginx for caching server-side rendered (SSR) web pages developed using React and Next.js

After creating an application where some pages are rendered on the server side, I noticed that something wasn't right. When viewing the requested pages in my browser, everything seemed normal. However, when I sent a CURL request to the page and saved ...

Using Vue.js to iterate through a limited number of elements from an array, filtered by category

I have a set of elements stored in an array and I am displaying them on a page using v-for: <template> <v-container> <v-layout row wrap v-for="offer in offers.slice((current_page-1)*5, current_page*5)"> ... </v-lay ...