Initialize data only when the Nuxt.js application is first loaded

Exploring the world of nuxt.js, I find myself pondering on the most efficient way to fetch data using REST api.

Within my store folder, the structure is as follows:

store
    -posts.js
    -categories.js
    -index.js

Initially, I attempted to set the data using nuxtServerInit actions in the index.js:

export const actions = {
    async nuxtServerInit({ dispatch }) {
        await dispatch('categories/setCategories')
        await dispatch('posts/loadPosts','all')
        
      }
}

Unfortunately, this approach did not yield the desired results; although the actions were dispatched on the server, the data was not properly set. As such, I turned to utilizing fetch, albeit encountering the issue of it being triggered every time the page containing posts was loaded. This persisted despite implementing a general layout configuration like so:

<template>
  <div>
    <Header />
    <keep-alive>
      <nuxt/>
    </keep-alive>
    
  </div>
</template>

Consequently, I resorted to employing a workaround by utilizing fetch within the page component:

 async fetch({store}){
       if(store.getters['posts/getPosts'].length === 0 && store.getters['categories/getCategories'].length === 0 ){
            await store.dispatch('categories/setCategories')
            await store.dispatch('posts/loadPosts','all')
       } 
   }

An observation worth noting is that fetch appeared to be ineffective when applied to the root page component (pages/index.vue).

Although my current solution appears to suffice, I am curious if there exists a more optimal method for setting the data?

Answer №1

There is no one-size-fits-all solution for this problem, as it largely depends on your specific requirements and needs. In my approach, I made a slight modification to your original solution by introducing a new variable loaded in each store module. Data retrieval will only occur if the loaded variable is set to false. This method works well for applications with user-generated content and authentication requirements. It is compatible with both server-side rendering and client-side rendering, preventing unnecessary data fetching on page visits where the user has no data.

An alternative way to simplify your fetch method is:

async fetch()
{
    await this.$store.dispatch('posts/getOnce')
}

The posts.js store module can be updated as shown below:

export const state = () => ({
    list: [],
    loaded: false
})

export const actions = {
    async getOnce({ dispatch, state }) {
        if (!state.loaded) {
            dispatch('posts/get')
        }
    },
    async get({ commit, state }) {
        await this.$axios.get(`/posts`)
            .then((res) => {
                if (res.status === 200) {
                    commit('set', res.data.posts)
                }
            })
    }         
}

export const mutations = {
    set(state, posts) {
        state.list = posts
        state.loaded = true
    }
}

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

Struggling with the compilation of this Typescript code

Encountering a compile error: error TS2339: Property 'waitForElementVisible' does not exist on type 'signinPage' SigninPage code snippet: export class signinPage{ constructor(){ emailInput: { selector: 'input[type ...

Surprising outcomes encountered when playing audio with JavaScript

I've been diving into learning JavaScript and decided to create a simple web page. This page, when Pikachu (image) is clicked, plays an audio file. Similarly, if the string "Pikachu" is typed into the form, it should play the same sound, otherwise, i ...

Switching from Vanilla JS to Vue.js, dealing with querySelector problems

Seeking assistance with transforming the following CodePen example to a Vue.js component: https://codepen.io/kjbrum/pen/qooQJJ While attempting to incorporate this.$nextTick for handling DOM manipulation, I'm encountering challenges in making it func ...

Issues with dynamically generating buttons using Ajax and Javascript technology

In order to dynamically create buttons based on the contents of a text file during the onload event, I have written a JavaScript function. However, despite being able to read the file and using alert messages to verify the correctness of the variable &apos ...

Unable to detect hover (etc) events after generating div elements with innerHTML method

After using the code below to generate some divs document.getElementById('container').innerHTML += '<div class="colorBox" id="box'+i+'"></div>'; I am encountering an issue with capturing hover events: $(".colorB ...

Place a gap at a specific spot within the boundary line

Here is a CSS code snippet that displays a horizontal line: .horizontalLineBottom { border-bottom:solid #6E6A6B; border-width:1px; } Is it possible to add space at a specific position on this line? For example, _________________________________ ...

"Is there a way to initiate a Date Picker with the current date using Javascript in an AngularJS application

I am having an issue with my date picker where the month starts from the current month and goes up to the next 12 months. However, I only want to display dates from the current date to the last date of the current month. I believe I need to set a limit so ...

The most effective method for transferring a JavaScript object between a TypeScript frontend and a Node.js backend

I need some advice on how to effectively share a JavaScript object between my Angular2 with Typescript frontend and NodeJS backend in an application I'm working on. Currently, I am using a .d.ts file for the frontend and adding a module.exports in the ...

Tips for transferring form data between pages using ReactJS?

Custom Checkout Implementation This section pertains to the custom checkout implementation utilizing Javascript. The goal is to extract form fields from the CheckoutForm page and utilize them within this checkout.js file for database submission. This pre ...

Unable to establish SocketIO callback from client to server resulting in a null object instead

I'm encountering an unusual issue with SocketIO. On the server-side, I am using the emit() method like this: $s.sockets.emit(scope, {some: datas}, function(feedback) { console.log('received callback'); } ) ...

How can I trigger an onclick event for a link automatically upon loading in Laravel?

I am presenting the link below: <a href="javascript:void(0)" onclick="xtenderSearchItem.modal_visibility = ! xtenderSearchItem.modal_visibility;">Request</a> My goal is for it to change the language of the page (which occu ...

Using Selenium Web Driver to extract information from Google's knowledge graph

Currently utilizing the Ruby Selenium web driver, my goal is to extract content from the Google Knowledge Graph located on the top right-hand side of the search results page. This element is within the <div class="xpdopen"> section. @driver = Seleni ...

What could be the reason why this LESS CSS is not taking effect?

Why won't this stylesheet load properly? The desired background color is supposed to be similar to cadetblue. You can view my page with the linked home.less.css at: ...

Is it possible to use a shell script to replace the external CSS file link in an HTML file with the actual content of the CSS file

Seeking a solution for replacing external CSS and JS file links in an HTML document with the actual content of these files. The current structure of the HTML file is as follows: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C ...

The model fails to bind when JSON is sent to the MVC controller

I've been facing an issue with my JSON payload not getting binded in my controller. I attempted creating a class with List<Models.UpdateChatRequestModel> Chats, but that didn't work for me. I also tried using an array name, but that approac ...

Jumbling a word by shuffling its letters into a random order

The objective of the program is to take the word you input into a box, split it into an array of letters, and then shuffle them. Following that, it should capitalize the first letter and lowercase the rest before displaying the result in the same box. I a ...

Patience is key as you await the element to load and smoothly render the data in vue.JS

Is there a way to ensure that the graph is only rendered and filled with data after the data has been returned from the backend? Currently, even though the data is returned, the graph appears blank. Here is my JavaScript code: methods: { refresh( ...

Guide on establishing two loops in React JS

I'm receiving a JSON array that contains nested arrays. I attempted to iterate through it using two loops, but so far, I haven't been successful. {this.state.listOfAlarms && this.state.listOfAlarms.map((alarms) => {alarms.repo ...

Can you please highlight parts of the text and provide dialogue with additional information?

I am currently enhancing my blog and looking for a way to implement JavaScript functionality that will help highlight specific parts of my text and provide additional information, like: I am currently working on my laptop When the user clicks on "lapto ...

Acquiring a fresh scope in Angular via a different component

In my project, I am developing an app using a component-based approach with Angular 1.5.5. As part of this development, I am utilizing d3js to create some elements with the class .floating-node. For each of these nodes, I am creating a new $scope and appe ...