The route path consists of data that will be retrieved before entering the route

I am facing an issue with my router configuration. I have a dynamic Route that requires the last part of its path to be set after fetching data from a store call in beforeRouteEnter.

beforeRouteEnter (to, from, next) {
if(to.params.categoryId) {
  next(vm => {
    store.dispatch('getSearchResults', to.params)
      .then(res => {
        let category = res.data.categories.find(cat => cat.id == to.params.categoryId);
        to.params.CName = category.name;
        // to.path = to.path + `/${category.name}`;
        console.log(to)
      }).catch(err => false)
  })
}else next();

The current Route setup is as follows:

{
  path: 'directory/bc-:categoryId(\\d+)?/:CName?',
  name: 'SearchResults',
  component: () => import(/* webpackChunkName: "listing" */ '../views/SearchResults.vue')
},

I need to update the CName parameter in the Route to reflect the category's name from the fetched data so that the final route displays the category name after the Id.

Answer №1

It is recommended to create a route with 2 children - one for dispatching the Vuex action and another for transitioning to the second child component.

{
  path: 'directory/bc-:categoryId(\\d+)?',
  name: 'SearchResultsParent',
  redirect:
  {
    name: 'SearchResultsFetch',
  },
  component: WrapperComponent,
  children:
  [
    {
      path: '',
      name: 'SearchResultsFetch',
      component: FetchSearchResults,
    },
    {
      path: ':CName',
      name: 'SearchResultsList',
      component: ShowSearchResults,
    },
  ]
}
// WrapperComponent.vue
<template>
  ....
  <router-view />
  ....
</template>
// FetchSearchResults.vue
<script>
export default
{
  created()
  {
    this.fetchData();
  },
  beforeRouteUpdate(to, from, next)
  {
    this.fetchData();
    next();
  },
  methods:
  {
    fetchData()
    {
      store.dispatch('getSearchResults', this.$route.params)
      .then(res => {
        let category = res.data.categories.find(cat => cat.id == this.route.params.categoryId);
        this.$router.push({
          name: 'SearchResultsList',
          params:
          {
            categoryId: this.$route.params.categoryId,
            CName: category.name,
          }
        });
      }).catch(err => false)
    }
  }
}

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

Troubleshooting HTTP Response Body Encoding Problem in Node.js

When making HTTP requests with the native 'http' module, unicode characters are not displayed correctly in the response body. Instead of showing the actual value, question mark characters appear. Below is a snippet of the code that I am working w ...

tips for optimizing pdf size using nodeJs and vueJs

I am searching for a library for either NodeJS or VueJS that can help reduce the size of PDF uploads by users. Which library should I choose? Alternatively, I came across pdftron but it is not widely used and not free. I tried installing ghostscript4js ...

Create a social chat platform similar to Facebook by implementing a chat box feature with the help of AJAX, jQuery

Currently, I have developed a chat box with two persistent issues. Despite my attempts to rectify them, I am unable to find a solution. Below, I will outline my code, focusing on the HTML section where the chat box, chat text area, and chat members are dis ...

Passing a variable to a template in Node.js and express with hbs is causing an unexpected identifier error

I’m working on a Node.js Express app, and I’m trying to pass a variable when rendering my index.hbs file, like this: <!DOCTYPE html> <html> <body> Hello. <a href="/auth/facebook">Login with Facebook</a> {{ ...

Troubleshooting directive not functioning properly with AngularJS ng-click

My HTML img tag is not responding to ng-click when clicked. I'm puzzled by this issue occurring in masonryPictureView.html Main page - home.html <ng-masonry> <ng-picture ng-items="projectdescription.pictures"></ng-picture> </n ...

Troubleshooting: Issues with the functionality of ng-include in AngularJS

Hi there, I am new to angular js and I'm attempting to integrate a simple html file into my page. Below is the code I am using: <!DOCTYPE html> <html ng-app=""> <head> </head> <body ng-controller="userController"> < ...

Having trouble with the Jquery click event not functioning on an interactive image map in Chrome browser

I currently have an interactive image-map embedded on my website. Here is the HTML code: <div id="italy-map" class="affiancato verticalmenteAllineato"> <div id="region-map"> <img src="./Immagini/transparent.gif" title="Click on ...

Utilize Jquery to hide radio buttons, while allowing users to click on an image to display a larger version

My current HTML structure is restricted to SAAS, so I only have control over jQuery implementation. https://i.stack.imgur.com/OHB9K.jpg I am attempting to achieve a similar layout as shown in the image below. The main issue lies in how to (1) conceal ...

Unable to set initial values for Select Option in Redux-Form

I have implemented an update form using redux-form, where the form value is initialized using initialValues. For example: <DataEdit initialValues={ Data }/> The form in the DataEdit page looks like this: <Field name="Data.taxTitle" comp ...

Issue Detected at a Precise Line Number - Android Studio

Despite my numerous attempts to modify the specific line in question, including leaving it empty, turning it into a comment, or removing it entirely, the error message persists. I even went as far as deleting the class and creating a new one, but the same ...

How can I incorporate a feature in my Angular application that allows users to switch between different view types, such as days, using JavaScript

Greetings, community! I am currently utilizing version 5 of the fullcalendar library from https://fullcalendar.io/ in my Angular 9 application. I have noticed that the calendar offers various options to change the view type as shown below: https://i.stac ...

Error: The function wrapper.find().simulate('keypress', {key: 'Enter', keycode: 13}) is not working as expected

Let's discuss further about this query vue-btn isn't triggering on pressing the enter key I have designed a sign-in page where users can log in by pressing 'Enter' on the keyboard. Now, I aim to perform a unit test that simulates pres ...

Loading fonts in Nuxt.js production modeIn a production setting, making

While everything works perfectly during development with preload including fonts, images, and scripts, the issue arises when building for production. The fonts are not preloaded in the final build - everything is there except the fonts. render: { http ...

Hiding labels using JQuery cannot be concealed

Why isn't this working? -_- The alert is showing, but nothing else happens. <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeaderContent"> <script type="text/javascript"> if (navigator.userA ...

What is causing a single state update when setState is called twice in React?

It seems like I'm making a beginner mistake in React as I am trying to call the "addMessage" function twice within the "add2Messages" function, but it only registers once. I believe this issue might be related to how hooks work in React. How can I mod ...

Printing in HTML is limited to only one page

While printing an HTML table that can vary in length, I often encounter the issue of it printing multiple pages. Is there a way to limit the printing to just one page through coding? Yes, you can achieve this by using the option in the browser print dialog ...

Generating a dynamic model name within a Vue v-for loop

While working on my application using Vue and Laravel, I encountered an issue within a v-for loop. I needed to bind error.id in the loop to the v-model name of the elements. Here is the relevant code snippet: <tbody class="bodycol"> <tr v-for=" ...

What is the best way to insert an object at a particular position within an array containing numerous nested objects?

This is the given Object: [ { "id": "1709408412689", "name": "WB1", "children": [ { "id": "1709408412690", "n ...

What is the best way to display changing session variables in PHP?

Purchase Page: This page allows customers to select business card orders in various foreign languages and customize their options. Whenever a user decides to add an extra card by clicking a button, javaScript dynamically includes new form fields. To ensur ...

Discovering checkboxes in HTML using jQuery

Greetings! I have limited knowledge when it comes to using jQuery. I am currently facing an issue with the Checkbox attribute. Below, you will find the code snippet that I have mentioned: Code: $( this ).html() Output: <input name="cb_kot[]" class= ...