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

Managing value state with several Formik forms within a single component

I'm currently in the process of constructing a web page using React and Formik. Within this form page, I have integrated three distinct Formik forms that are conditionally displayed based on a switch statement. The reason behind structuring it this wa ...

Error occurred in custom directive library due to unhandled TypeError

I have developed a personalized directory for tooltips and I am looking to turn it into a reusable library that can be imported and utilized in various projects. I have successfully created the library and imported it into different projects. However, upon ...

Choose all the checkboxes alongside the markers on Google Maps

On this page , I have included a checkbox labeled "Select All" at the bottom, which automatically checks all other checkboxes. Although the code below achieves what I want, the marker icons are not showing up. How can this be fixed? $(document).ready(func ...

Guide to dividing a string and structuring it into an array

I need help breaking apart these strings: var str = '(john) the quick brown (emily) fox jumps over (steam) the lazy dog.' var str1 = '(john) the quick brown fox jumps over (steam) the lazy dog.' to create an array like this: joh ...

json request not functioning properly in Internet Explorer and experiencing difficulties with caching

Unfortunately, the code snippet provided below is compatible only with Firefox and not Internet Explorer. The JSON file breaks when it encounters the text "Meanscoil na mBraithre Criostaí": "2028425":[19, "Awaiting Correction", "", "Meanscoil na mBra ...

Using the window.prompt function to send information to specific fields in a MySQL database is not functioning correctly. I am looking for assistance with this issue

Currently, I am attempting to send some data to a server that is MySQL-based. After running the code below, it seems like there are no errors showing up in the console. Can you please review this code and let me know if you spot any issues? I would really ...

Transforming a JSON file that has been previously converted to an Observable into a TypeScript map within an Angular application

There is a json data file named dummy, with the following structure: [ {"key":"KEY1", "value":["alpha","beta","gamma"]}, {"key":"KEY2", "value":["A","B","C"]}, {"key":"KEY3", "value":["One","Foo","Bar"]} ] The goal is to convert this json f ...

Utilizing React JS to Export Axios Response

I have an getAllUsers.js File that retrieves all users from the API. import axios from 'axios' export const fetchData = async () => { let response try { response = await axios.get('http://127.0.0.1:8000/api/users') } catc ...

HTML - implementing a login system without the use of PHP

While I am aware that the answer may lean towards being negative, I am currently in the process of developing a series of web pages for an IST assignment in Year 9. Unfortunately, the web page cannot be hosted and our assessor lacks the expertise to utiliz ...

Tips on retrieving a value nested within 3 layers in Angular

In my Angular application, I have three components - A, B, and C. Component A serves as the main component, Component B is a smaller section nested inside A, and Component C represents a modal dialog. The template code for Component A looks something like ...

Having an issue with discord.js and node.js modules not exporting correctly? The returned statement is not functioning as

Trying to retrieve specific messages from a channel to gather information about registered 'clans' has been quite challenging for me. I am able to fetch the channel, filter and loop through the messages, but strangely, I cannot return the fetched ...

React: When mapping an array of state objects, not all states are displayed

I'm encountering an odd problem while using React. I'm currently developing a budget tracking app that includes a total budget, a form to add new expenses, and displaying those expenses with their costs below. The cost of the new expense will als ...

What is the best way to extract data from two dropdown menus and send it to separate URLs?

I need assistance with extracting the selected year value from the first dropdown. I would like to append this value to the URL of the header page and also to the options in the second dropdown. This way, when I select a PHP page from the second dropdown ...

Create a request for an update by utilizing Axios within a React and Material UI environment

I am completely new to React, and my experience with CRUD functionality is limited to ASP.NET MVC. I'm feeling a bit lost as none of the tutorials I've come across seem to cater to my specific situation. The tips I received previously were helpfu ...

Sending information from one page to another and then sending it once more

I am currently utilizing the following code to submit a form's data to : <script type="text/javascript"> $(document).ready(function(){ $("#textnextofkin").validate({ debug: false, rules: { ...

Interactive pop-up windows in Bootstrap

I encountered an issue with bootstrap modal forms where the form displays correctly after clicking on the button, but the area in which the form is displayed gets blocked! It's difficult to explain, but you can see the problem by visiting this link. ...

What are the distinctions between altering the value of a textarea with JS and user input?

I've come across an interesting scenario that I'm hoping someone with more expertise in JavaScript can help me with. There is a popular online forum site that I frequently use. In the past, I was able to easily update a comment textarea using Jav ...

Struggling to display the sorted array items on the screen?

Within the realm of my jsfiddle experiment, my aim is to organize items based on price from highest to lowest by utilizing the following function: function mySortingFunction() { var elements = [].slice.call(document.getElementsByClassName("price")); e ...

The navigation bar is positioned with white space above it

Currently working on a website design and facing an issue with adding a clickable button to the Nav-bar. Noticed some white-space above the Nav-bar which is not desired. I had previously posted a similar question but unable to identify the CSS error causi ...

PHALCON array entry now in place

Currently, I am facing an issue while trying to insert multiple data from an array. It seems that only the last piece of data is being inserted each time. Below is the front-end code snippet responsible for sending the data: let payload = new FormData(); ...