How to dynamically add content to VueJS/Nuxt template using Vuex state

I'm currently delving into the world of VueJS with an aspiration to construct an app that fetches content from a WordPress instance using VueJS, Nuxt and Vuex in conjunction with the WordPress REST API. I've managed to establish a connection with the API, retrieve the content through state, but unfortunately, I'm stuck on how to transfer that data from state to the template. Every attempt I make leads to "x is not a function" or "x is not defined" errors.

Despite scouring various blog posts online, I haven't been able to find a solution that resolves my issue. Where might I be going astray?

store/index.js

import Vuex from "vuex";
import axios from "axios";

const createStore = () => {
    return new Vuex.Store({
        state: {
            explore: null,
            pages: null
        },
        actions: {
            getExplore: function(context) {
                return new Promise((resolve, reject) => {
                    if (context.state.explore) {
                        resolve()
                    }
                    else {
                        axios.get(path_to_api_endpoint)
                        .then((response) => {
                            context.commit('storeExplore', response.data)
                            resolve()
                        }).catch((error) => {
                            reject(error);
                        });
                    }
                })
            },
            getSinglePage: function() {
                return new Promise((resolve, reject) => {
                    this.$store.dispatch('getExplore')
                    .then(() => {
                        var foundPage = false;
                        this.$store.state.pages
                        .filter((page) => {
                            if(pageName === this.$route.params.slug) {
                                this.singlePage = page;
                                foundPage = true;
                            }
                        });
                        foundPage ? resolve() : reject();
                    })
                })
            }
        },
        mutations: {
            storeExplore(state, response) {
                state.explore = response
            },
            storePages(state, response) {
                state.pages = response }
            }
    })
}

export default createStore

pages/explore/_slug/index.vue (Parent Component)

<template>
    <div>
        <layout-browserupgrade></layout-browserupgrade>
        <div class="wrapper" :toggle-nav="showHideNav" :class="navState">
            <layout-toolbar @showHideNav="showHideNav"></layout-toolbar>
            <layout-hero :pageRef="pageId"></layout-hero>
            <explore-detail></explore-detail>
            <layout-footer></layout-footer>
        </div>
        <layout-nav></layout-nav>
    </div>
</template>
<script>
...
...
...
</style>

I have temporarily excluded the data interpolation for testing purposes, just focusing on getting one section to function correctly.

If anyone could point me towards relevant documentation or provide insight into where I may be faltering, I would greatly appreciate it. Time is running short, and I am struggling to crack this puzzle.

Thank you!

Alex

Answer №1

Make sure to utilize the asyncData method in your pages. This function is unique to page components and is executed every time before the page component loads.

To incorporate axios, simply run npm i axios. Axios is a powerful library for handling asynchronous requests using promises.

In your pages/detail.vue file:

<script>
  import axios from 'axios'
  ...

  asyncData({ params }) {
    return axios
      .get(
        APIENDPOINT
      )
      .then(data => {
        return {
          data
        };
      })
      .catch(e => context.error());
  },

  ...
</script>

For detailed information, refer to the documentation at https://nuxtjs.org/guide/async-data

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

Encountering an issue with receiving "undefined" values while utilizing WordPress post metadata in AngularJS

Utilizing the Wordpress REST API v2 to fetch data from my functional Wordpress website to an AngularJS application. Everything is functioning properly, however when I attempt to access post meta such as "_ait-item_item-data", it returns an error stating "u ...

Tips for making an interactive slider using JQuery

I need to create dynamic sliders within tabs that can change content dynamically. My development platform is ASP.NET MVC 5 and I'm using JSON data format. What's the best way to implement this dynamic slider feature for each tab? <div class ...

Using HTML, CSS, and JavaScript, the main tab must include nested subtabs to enhance navigation and

When a user clicks on a tab, another tab should open within the main tab. Depending on the selection in the second tab, input fields should appear while others hide. Something similar to the nested tabs on expedia.com. I have experimented with the tab vie ...

Chart JS fails to update when computed property changes

I have a computed property named drilldownData: computed: { drilldownData() { if (this.toggle_drill === "up") { return this.waterfallDataSmall } else { return this.waterfallData } } } The toggle_dri ...

Struggling to eliminate HTML tags from a string containing the 'aspNetHidden' CSS class

I have a web user control that is being compiled into HTML. The issue I am facing is that the HTML is returning with view states enclosed in DIVs with a class of aspNetHidden. These DIVs are causing problems with my page's design, so I am attempting t ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

What is the best way to give a fixed height to Card content in Material UI? Is CSS the way to go?

I've been struggling with a design issue involving Material-UI cards used to display News. The problem arises when the paragraph section of the card occupies multiple lines of text. When it spans two lines, there is a 10px spacing between the paragrap ...

The AngularJS application appears to have trouble accessing a local text file, even when it is deployed on

Within the same directory of my application deployed on IIS, there are 4 files: home.html Angular.js data.txt web.config (Automatically generated by IIS for default document) I am looking to display the content of 'data.txt' on 'home.html ...

Identify similarities between two elements within an array, and if specific attributes align, modify the property of the first element

I am facing a challenge with two large arrays in my project. allInventoryItems.length //100,000 objects `allInventoryItems[0] // { name: 'Something', price: 200 } along with currentInventory.length //~250 objects `currentInventory[0] / ...

Output the initial value and subsequently disregard any values emitted during a specified time interval

Check out my code snippet: app.component.ts notifier$ = new BehaviorSubject<any>({}); notify() { this.notifier$.next({}); } app.component.html <div (scroll)="notify()"></div> <child-component [inp]="notifier$ | async" /> ...

The function "toggleHeightAndOpacity" cannot be accessed on this object because it is not defined

I'm attempting to invoke a variable function name, a task I have successfully accomplished many times in the past using code similar to that found here. <script type="text/javascript"> $.fn.toggleHeightAndOpacity = function(show) { ...

Is there a way to collect and store all Objects that come through an on-click event in an array whenever the button is clicked?

In my attempt to iterate over a button within a map function, I am aiming to collect all the values in an array obtained after each click event. The structure of the map function is as follows: {Data.map((d, i) => { return ( <div key={ ...

What could be causing my YouTube code to malfunction with certain playlists?

Check out the first jsfiddle playlist here The Alum Songs Playlist is working perfectly, but unfortunately, the same code is not functioning for another playlist ID. View the second jsfiddle playlist here The Medical Animated Playlist is currently not w ...

The conditional rendering in VueJS using v-if for array[index] doesn't seem to be

I have a vision for creating a component that displays a text-box when the mouse hovers over an image. Here is the HTML template I came up with: <section class="item-container" v-for="(item, index) in items"> <div class="image-box" @mouseenter ...

JavaScript guide: Converting an array structured by tuples into a multidimensional array

I'm working with an array, X[(i,j,l)], which is indexed by 3-dimensional tuples where i and j range from 1 to n, and l ranges from 1 to "layers". This binary array consists of elements that are either 0 or 1. The array was generated as a result of so ...

I have been struggling to make react-hook-form validate my input correctly ever since I moved the input to its own component

I have a Form.js component that generates a form element. Inside this form element, there is a FormGroup component that accepts props like inputType, inputName, inputPlaceholder, and renders an input field with a label. I am using react-hook-form for input ...

unique color schemes for pie charts with nvd3-angular

I'm attempting to personalize the colors of a pie chart by utilizing the angular-nvd3 extension. I discovered the issue in the plunker example. Although I was able to customize the color of the legend, the chart itself remained unchanged. I would li ...

Instructions for implementing tooltips on a pie chart slice when hovering with the mouse pointer, using the canvas

var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var cw = canvas.width; var ch = canvas.height; ctx.lineWidth = 2; ctx.font = '14px verdana'; var PI2 = Math.PI * 2; var myColor = ["Gr ...

"Is it possible for the package-lock.json file to not update when a package is removed from the

When I add a package manually to my package.json file and run npm install, the dependencies of that new package are updated in my package-lock.json. However, if I then delete that package from package.json and run npm install, the dependencies of that pac ...

Installing Vue JavaScript using the npm command

Embarking on my journey as a Vue JS learner, I took the plunge to install Vue and delve into creating web applications using it. So, I globally added npm Vue. npm install --global vue-cli This action resulted in: npm WARN deprecated [email protected]: T ...