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

Get a CSV file through EmberJs

I have been experimenting with various function calls, but I am unable to figure out how to initiate a CSV download in EmberJs. Below is the most recent code I have tried: let endpoint = '/api/foo/'; let options = { url: endpoint, type: ...

Troubles with showcasing user attributes in the view with ng-repeat and handle-bars in Angular.js

React.js, Express.js, MongoDB server.js: const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const routes = require('./routes/index'); const users = ...

When making an Ajax request to another website, the response received is in HTML format instead of

I am attempting to retrieve an array by making an AJAX GET request to a URL. Below is my controller code, which is hosted locally at localhost:3000 def merchant_ids merchants = Merchant.where(id: params[:id]).pluck(:merchant_name, :id, :merchant_city, ...

The final piece left in stitching together an array

Issue I have been struggling with this code for some time now and I can't seem to figure out the solution. I am receiving 3 values from inputs and trying to remove all the empty spaces "" in the array, but when I execute the code, it displays the foll ...

Ways to eliminate the absence of the 'Access-Control-Allow-Origin' header in an error message when using a Java-based web-service server

I'm currently working on developing a webservice using Java as the server and Javascript as the client. My goal is to send a Post request with JSON data and receive a Post response with JSON data from the server. However, since the client and server h ...

Perform time update every second

Is it feasible to have my timeupdate function run every second? (Using VUE CLI) @timeupdate="videoSecond" videoSecond(){ let Second = this.player.currentTime(); let CaptureList = this.capturesList; CaptureList.forEach(element => ...

Dealing with submit errors in React Redux forms

I am facing a challenge with handling exceptions properly when submitting in redux forms. I want to display a toast message when an error occurs. LogIn.js: class LogIn extends PureComponent { onSubmit = (values) => { const { login } = this.props; ...

Timeout for AngularJS Bootstrap UI Modal

I am having some trouble with opening a bootstrap modal using the $timeout function. The issue I am facing is that the modal keeps opening multiple times as the timeout fires repeatedly. Any assistance or suggestions on how to resolve this problem would be ...

interactive textbox created with the combination of javascript and php

Hello, I am new to JavaScript and jQuery. I am trying to create a dynamic text box using JavaScript that can add and remove rows. When I press the add button, it works well, but when I pressed delete, it deleted the entire table. Below is my JavaScript fu ...

Store <td> in a variable

At the moment, I have a script that allows users to input an item name, along with its size, color, and other options. Each of these entries is saved as individual items with their custom specifications, such as a black t-shirt in large size. The script c ...

Tips for initiating a component within a loop and terminating it after completing all 3 iterations

Looking for a solution to open and close tags in a loop every 3 iterations. The objective is to create a grid using container, row, and column elements. However, I am unsure how to achieve this. Example: render(){ const arrayName = ["john", " ...

Utilizing multiple sticky columns in BootstrapVue with Vue.js

I am facing an issue with multiple sticky columns in my layout. When these columns are set as sticky, they tend to visually stack over each other, sometimes causing the left-most sticky column to "peek" out from under the next one. Is there a way to add m ...

Modify the onerror function of the image tag within the onerror function

Here is a way to display images using the img tag: If 1.jpg exists, show 1.jpg. If not, check for 2.jpg and display it if it exists. If neither 1.jpg nor 2.jpg exist, display 3.jpg. <img src="1.jpg" onerror="this.src='2.jpg'; this.oner ...

Checking the existence of a user's email in Node.js

Hey there! I am new here and currently learning Node.js with Express. I'm trying to find a way to check if a user's email already exists in the database. Here is what I have so far: const emailExists = user.findOne({ email: req.body.email }); if ...

Creating an external JavaScript and CSS file for date picker in Eclipse can be done by following a few simple steps. By creating separate files for the

I am using the following javascript and css styles: <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all" /> <script src="http://ajax.googleapis.com/ajax/libs/jq ...

How can Vue.js transfer form data values (using v-model) from a Parent component to a Child component?

I am working on a multistep form using vue.js. The parent form collects two inputs and once these are validated, it moves to the next step which involves a child component. I want to pass the values from the parent component to the child component's f ...

Tips for calculating the canvas-relative mouse position on a CSS 3D transformed canvas

Recently decided to challenge myself by experimenting with drawing on 3D transformed canvases. After some trial and error, I managed to get it partially working. const m4 = twgl.m4; [...document.querySelectorAll('canvas')].forEach((canvas) =& ...

"Automate the process of manual content duplication with JavaScript's for each replacement

Seeking a solution to automate the selection process without writing individual JS scripts for every input. For instance, having 10 double inputs (total of 20 inputs) and utilizing the each() function or other methods by only declaring selectors. Find th ...

Exploring the World of Next.js and Sequelize Model Relationships

Greetings to all the problem-solving enthusiasts out there! I'm currently in the process of revamping a previous project using Next.js, and I've hit a roadblock that has me stumped. My current challenge involves establishing an association betwe ...

Bringing in a script and invoking a function on a specific variable

As a newcomer to Typescript, I've been experimenting with some code I came across online to enhance the appearance of links on my website. <script src="https://wow.zamimg.com/widgets/power.js"></script> <script>var wowhead_tooltips ...