Nuxt with Laravel API Integration

I am working on pulling in two separate data sets within the store directory. I plan to create a categories list and an events list.

Initially, I began with a single set in the index.js file.

export const state = () => ({
    categories: []
  })
  
  export const getters = {
    categories (state) {
      return state.categories
    }
  }
  
  export const mutations = {
    SET_CATEGORIES (state, categories) {
      state.categories = categories
    }
  }
  
  export const actions = {
    async nuxtServerInit({ commit, dispatch }) {
      let response = await this.$axios.$get('categories')
  
      commit('SET_CATEGORIES', response.data)
    }
  }

This setup is functioning as expected.

I transferred it to a category.js file and modified index.js to look like:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

import category from './category'

export default new Vuex.Store({
  modules: {
    category
  }
})
 

While I anticipate receiving the same list of categories as before, I encountered an error stating 'Cannot read properties of undefined (reading 'getters')'. This approach was suggested on an older Laracasts Forum.

After revisiting the Nuxt documentation, it appears that the structure should be more along the lines of:

import category from './category'

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

Upon implementing these changes, the error disappeared but I still did not receive any data. However, this format does not seem quite right either.

I have been exploring similar solutions and going around in circles without finding a suitable solution yet. Any suggestions or ideas?

Answer №1

Forget about using index.js to register modules with Nuxt - it automatically handles any *.js file (excluding index) in the /store/ directory as a module.

For example, /store/category.js will register state under this.$store.state.category, and actions can be dispatched like

this.$store.dispatch('category/getCategories')

According to the documentation:

Each .js file inside the store directory is treated as a namespaced module (with index as the root module).

Learn more about setting up your store in Nuxt: 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

Angular JWT token validation error

I am currently experiencing an issue with the Angular JWT token. It works perfectly fine on my API when tested using Postman, but for some reason it is not working when called from Angular. Here are the request details: https://i.sstatic.net/L6Tsr.png I c ...

Having trouble with Autocomplete Search feature in Laravel?

I have a search field with the same name and id on both my categories page and products page. The autocomplete suggestions are working fine, but when I click on a suggested product in the search field, it stays on the same page instead of redirecting me to ...

Neglecting the Outcome of Async/Await

I am facing an issue where I need to send different SMS messages to different recipients synchronously, but my current implementation using async/await is not producing the expected results. Below is the code snippet causing the problem: Upon querying fo ...

Ignore BBCode Within Code Blocks

I have searched through various resources on this particular issue, but none of them have provided the solution I am looking for. Currently, I am in the process of developing my own BBCode parser. However, I am facing a challenge regarding excluding the B ...

"Bootstrap Toggle malfunctioning when switching between disabled and enabled states on a restricted set of

Having an issue with the Bootstrap Toggle Library in combination with Bootstrap 4. I am trying to restrict users from switching 'ON' more than a set number of elements. Here is the snippet of my HTML code: <div style="border:solid border-widt ...

Is it possible to display this code through printing rather than using an onclick event?

I have a puzzle website in the works where users select a puzzle to solve. I am looking for a way to display the puzzles directly on the website instead of using pop-up boxes. I am proficient in various coding languages, so any solution will work for me. ...

Adjusting the drag mouse position in jqueryUI

I'm currently working on coding a Lockscreen design inspired by ios8. I want to create a draggable element that only moves along the x-axis. $( "#IDlsDragable" ).draggable({ axis: "x" }); .lockscreen { position:fixed; top:0px; left:0px; wid ...

Steps to extract a portion of a URL and display it in the "src" attribute

Here is the URL: My Code: (please refer to the JS comments for instructions on how to complete steps 2 and 3) <script> function mdlbox() { //step 1: Show the modal box var y = document.getElementsByClassName('modalDialog'); ...

What is the best way to execute two asynchronous operations simultaneously in Node.js, treating them as a single atomic operation?

In my current setup, I have a function that calls two asynchronous functions. This main function is responsible for handling user requests. Let me show you an example: mainFunction(req, res, done) { asyncExist(req, function(exists) { if (!exists ...

Is it considered poor form for an Angular controller to invoke a function on a directive?

My custom Angular directive functions as a unique combobox, where clicking on the input control reveals a div below it with a list of items from a model object. The user can type text into the input control to filter the displayed list. In addition to the ...

What could be the issue with my interactive dropdown menu?

I am currently experiencing an issue with a drop down list that is supposed to fetch records from a column in another table, but no records are appearing. Additionally, I would like to add an option in the drop down list labeled "others" for users to inp ...

Is there a way to detect a class change using jQuery?

Below is an example of a div: <div id="components-reconnect-modal" class="components-connecting-show"> <div id="1"> <div id="2"> <div id="3"> <div id="4"> </div> The ID will remain constant, but the class will ...

Display the second dropdown after the user has made a selection in the first dropdown

Recently, I've been delving into the world of html/javascript and navigating through the process of implementing the code found in this specific link. While I can see the solution outlined in the link provided below, I'm struggling with how to i ...

Is it possible to manually trigger a refresh/render for a specific URL in Vue.js?

When accessing the URL "example.com/abc", is it feasible to have the page reload instead of updating the DOM? All other URLs should function as normal, but for /abc in particular, the page should refresh or re-render. ...

The Three.js effect is functional on Firefox but experiencing issues on Chrome

I have recently implemented a recursive search for adjacent faces using a Half Edge data structure and I am facing an issue where the effect is visible on Firefox but not on Chrome. I am seeking assistance in resolving this problem. Any help or suggestions ...

When attempting to run `npm install`, an error message is received indicating a network connectivity issue: "npm ERR

When I try to run npm install, I encounter an error. Here is the error message: 71 error code ETIMEDOUT 72 error errno ETIMEDOUT 73 error network request to https://registry.npmjs.org/@angular%2fanimations failed, reason: connect ETIMEDOUT 151.101.112.16 ...

"Transferring a C# dictionary into a TypeScript Map: A step-by-step

What is the correct way to pass a C# dictionary into a TypeScript Map? [HttpGet("reportsUsage")] public IActionResult GetReportsUsage() { //var reportsUsage = _statService.GetReportsUsage(); IDictionary<int, int> te ...

Does jQuery UI Layout have compatibility issues with jQuery version 3.3.1?

jQuery UI Layout is compatible with older versions of jQuery, but not with newer versions... Here is a working example: <html> <head> <script src="http://layout.jquery-dev.net/lib/js/jquery-1.4.2.js"></script> <script ...

Error in sorting the table within an expandable table feature in CodeIgniter

I've been working on a way to make my table data sortable within an expandable table view. I attempted using the code provided in the link below: Code Link My current view looks like the image shown below. However, after implementing the code on my ...

Transferring ipywidgets to a web platform

I've developed a Python program in Jupyter Notebook that leverages the interact function from the ipywidgets module. interact(my_func, filter_by=filter_by_list, format_type=format_dict.keys()) I am looking for a way to share this interactive widget ...