When navigating between Dynamic Pages using NuxtLink, the store data is not accessible

Check out the demo below.
Click here for stackblitz

When transitioning from a top page to a post page, the correct content is displayed. However, moving from one post page to another does not display the correct content immediately. Reloading the page will show the correct content.

Could you guide us on how to ensure the correct content is displayed when transitioning between different post pages?


The code for the submission page is as shown below:

// pages/post/_id.vue
<template>
  <div></div>
</template>

<script>
import { fetchPosts } from '../../lib/post';

export default {
  name: 'Post',
  layout: 'post/index',
  async asyncData({ route, store }) {
    const posts = await fetchPosts();
    const post = posts.find(({ id }) => id === route.params.id);
    store.dispatch('setPost', post);
    store.dispatch('setPosts', posts);
  },
};
</script>
// layouts/post/index.vue
<template>
  <div>
    <h1 v-if="post">{{ post.title }}</h1>

    <p v-if="post">{{ post.title }} page</p>

    <ul>
      <li v-for="post in posts" :key="post.id">
        <NuxtLink :to="'/post/' + post.id">
          {{ post.title }}
        </NuxtLink>
      </li>
    </ul>

    <NuxtLink to="/">Return to Top</NuxtLink>
  </div>
</template>

<script>
export default {
  data() {
    return {
      post: null,
      posts: [],
    };
  },
  created() {
    this.post = this.$store.getters['post'].post;
    this.posts = this.$store.getters['posts'].posts;
  },
};
</script>

The process flow is outlined below:

  1. The pages retrieve data from the server and dispatch it to the store
  2. The layouts fetch data from the store and display it accordingly

While unconventional, my current project mandates the use of pages and layouts in this manner, leaving me unable to alter the setup.

Answer №1

The reason for this behavior is that the layout was pre-rendered before the route changed, so the hook isn't triggered again. One way to solve this is by adding a watch for the route like so:

...
  watch: {
    '$route': function (newValue) {
      this.article = this.$store.getters['article'].article;
      this.articles = this.$store.getters['articles'].articles;
    }
  },
...

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

Displaying a preloaded image on the canvas

Once again, I find myself in unfamiliar territory but faced with the task of preloading images and then displaying them on the page once all elements (including xml files etc.) are loaded. The images and references are stored in an array for later retrie ...

Struggling with eliminating spacing between v-text-field elements and labels in Vuetify

Struggling to reduce the vast gap between rows in my Vuetify project. I've attempted using CSS and Vuetify spacing options, but haven't had any luck. Desired layout: Current layout: <v-container> <v-row> <v-col cols=" ...

Failed to validate user profile because of an InternalOAuthError error while using passport-facebook-token to verify the token

In my iOS application, I am utilizing the Facebook API for user login and receiving an access token in return. Now, I need to use this token to verify a user on my backend server. For this purpose, I have implemented the passport-facebook-token strategy w ...

Having trouble with Vue 3 Component State not updating following an asynchronous operation?

Encountering challenges in my Vue 3 app when trying to update a component's state post an asynchronous operation. Here's what's happening: Within a component, there is a method called containerMoveHere that utilizes Socket.io for an async o ...

tslint issues detected within a line of code in a function

I am a novice when it comes to tslint and typescript. Attempting to resolve the error: Unnecessary local variable - stackThird. Can someone guide me on how to rectify this issue? Despite research, I have not been successful in finding a solution. The err ...

How to properly declare an explicit injector when using the resolve parameter in $routeProvider?

$routeProvider resolve feature in AngularJS allows for injecting additional dependencies to the controller function. How can we combine this with explicit dependency injection declaration? Example: angular.module('myModule', []) .config(func ...

Is there a navigation feature in VueJS that functions similarly to React Router?

I am currently working on enhancing the navigation experience of an existing vueJS application that utilizes Vue Router. When working with React, I typically structure breadcrumbs in the following manner: <Breadcrumbs> <Route path="/users&q ...

Looping animations using AngularJS

I have implemented a custom directive to trigger an animation on an element when a specific field is empty on the page. However, I am facing an issue where the animation only works once when the user clicks the button with the directive. Subsequent clicks ...

The length of JSONPath in Javascript is significantly longer, approximately 3000 times lengthier than a traditional loop

I am experiencing performance issues with JSONPath implemented in JavaScript using the Stephan Goessner Library. Below is an example of the JSON structure causing the problem: [ { id:1, name: "lorem", elements: [ ...

Retrieve components of Node.js Express response using axios before terminating with end()

Is there a way to receive parts of a response from my nodejs server before res.end() using axios? Example: Server router.get('/bulkRes', (req,res)=>{ res.write("First"); setTimeout(()=>{ res.end("Done"); },5000); }) Cl ...

What are some methods for submitting an HTML form to a CSV file?

I've been racking my brain for the past few days trying to find a viable solution to this problem. My project requires 100 individuals to take turns sitting at a computer and filling out a form I created. Each time someone submits their information, ...

Using jQuery to iterate through rendered HTML with the ForEach function

I am utilizing JS/jQuery code to extract the cell value of an ASP DetailsView control (rendered HTML), validate it against a condition, and hide a specific div based on the result. Specifically, the code is examining whether the cell value is formatted lik ...

How can you optimize the storage of keys in JS objects?

Just pondering over this scenario: Consider a line definition like the one below, where start and end are both points. let ln = { s: {x:0, y:0}, e: {x:0, y:0}, o: 'vertical' } Now imagine having a vast array of lines, how can we sav ...

What is the process for transitioning data between SQL, PHP, and JavaScript seamlessly?

As a developer who frequently works on SQL/PHP applications, I often find myself constantly rewriting JavaScript code to accomplish the same tasks repeatedly. When dealing with simple APIs, it's not too difficult to create one-off AJAX methods to comm ...

Customize bullet list icons to adjust in size based on content using css

In my CMS project, the CMS team has a special requirement regarding unordered and ordered lists. They want the size of the bullet list icon to adjust according to the text content within the list. The image below shows the default design of a list item: ...

What is the best way to display label information on a Google line chart?

line graph column graph My graph continuously calls the Controller to fetch recent data from the Database. There are two lines on the graph, and I would like to display the names of each line (column) such as red=counts of something // brown=counts of so ...

The hidden DIV containing an ASP.NET CheckBox consistently yields a value of false

I have a group of form elements located within a hidden div which looks like this: <div id="jDivUpdateFolder" style="display:none;"> <asp:TextBox ID="txtEditFolderName" runat="server"></asp:TextBox><br /> <asp:TextBox ID ...

Creating a service function (constructor) in JavaScript

When working with AngularJs and calling a service method: app.service('nameService', function() { this.Service = function (){console.log('hello')} } You can then use this service (object) like so: nameService.Service() My question is, ...

Utilize Object literal manipulation to include properties in a specific sequence

Working on a tool to generate Nassi-Shneiderman diagrams online, where each diagram is represented as an object literal with unlimited possible children. As I aim to add a sequence into the while loop following the first sequence, I encounter the challeng ...

Steer clear of wrapping ng-repeat in nested indexes for routing purposes

I am currently working on an Angular application that displays data in 3 item columns using Bootstrap. To achieve this layout, I have implemented the following code snippet to group my array of data into sets of 3: examples.success(function(data) { $sc ...