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

Challenge encountered with asynchronous angular queries

Dealing with asynchronous calls in Angular can be tricky. One common issue is getting an array as undefined due to the asynchronous nature of the calls. How can this be solved? private fetchData(id){ var array = []; this.httpClient.get('someUrl ...

Executing several GET requests in JavaScript

Is there a more efficient way to make multiple get requests to 4 different PHP files within my project and wait for all of them to return successfully before appending the results to the table? I have tried nesting the requests, but I'm looking for a ...

Personalized dropdown appearance

During my work on a select box, I discovered that custom styling is not possible. I attempted to use some plugins but did not find one that met my needs. I am seeking a dropdown menu with options in both black and gray, similar to this template but using ...

Is it possible to execute an npm package without using the npm run command?

Is there a way to initiate the next.js build process directly through the command line without needing to use the package.json file? Can we execute it without relying on npm run? Perhaps running next build in the command line could achieve this instead of ...

Altering Image Order Across Various Slides

I have customized a parallax website template that is divided into various sections and slides. I want to incorporate a fixed image sequence on each slide that animates based on the scroll position. With 91 images in the animation sequence, it moves quickl ...

Is there a way to manipulate the DOM without relying on a library like jQuery?

My usual go-to method for manipulating the DOM involves jQuery, like this: var mything = $("#mything"); mything.on("click", function() { mything.addClass("red"); mything.html("I have sinned."); }); Now I am looking to achieve the same result usin ...

Guide to extracting the outcomes of a promise array and populating them into a new array using Protractor

I am facing a challenge with transferring data from an array of promises generated by the following code: element.all(by.repeater('unit in units')). It seems to be difficult for me to store this data into another array: element.all(by.repeater(& ...

The selected jQuery plugin is not functioning properly within CodeIgniter framework

I recently downloaded the jQuery Chosen plugin to use the simple "multiselect" version on my website. I followed all the necessary steps and even copied and pasted the code into CodeIgniter. Despite my experience with jQuery, I am facing an issue where the ...

Tips for displaying a dropdown on top of a modal with the help of Tailwind CSS

I am currently utilizing Tailwind CSS and I am struggling to display the white dropdown over my modal. Despite attempting to use the z-index, I have been unsuccessful in getting it to work. Do you have any suggestions or insights on how to resolve this is ...

What is the correct placement for $.validator.setDefaults({ onkeyup: false }) in order to deactivate MVC3 onKeyup for the Remote attribute?

After coming across various solutions on how to disable the onKeyup feature of MVC3 Remote Validator, I noticed that many suggest using the following code: $.validator.setDefaults({ onkeyup: false }); However, I'm in a dilemma about where to place t ...

Error: Vue is unable to access the property '_modulesNamespaceMap' because it is undefined

I've been working on a simple web app to enhance my testing skills in Vue using Vue Test Utils and Jest. However, I encountered an error related to Vue while trying to console log and check if AddDialog is present in my Home file. The error message I ...

Ways to showcase a variable's value in conjunction with text using .html() method

Hello, I need assistance with printing a value in a popup window. Below is the code I am using: "code" $('#warning').html('<p style="font-size: 12px;padding-top: 13px;">The updated list value is <p>' + var11); https://i.s ...

Custom headers in XmlHttpRequest: Access control check failed for preflight response

Encountering an issue with an ajax GET Request on REST Server. Test results and details provided below. There are two methods in the REST Server: 1) resource_new_get (returns json data without custom header) 2) resource_api_new_get (also returns json d ...

Modifying the state of a store through a component

I'm currently facing an issue with a table in my application that displays objects from the store. When I click on a table row, I want to be able to change a specific value in the state from false to true so that I can populate another table with deta ...

The error occurred while trying to cast the value of "{{Campground.name}}" to an ObjectID. This value, which is of type string, could not be converted to an ObjectID at the path "_id" for

const express = require("express"); const session = require("express-session"); const cookieParser = require('cookie-parser') const mongoose = require("mongoose"); const { Campground, User, Review } = require(" ...

What options are available for managing state in angularjs, similar to Redux?

Currently, I'm involved in an extensive project where we are developing a highly interactive Dashboard. This platform allows users to visualize and analyze various data sets through charts, tables, and more. In order to enhance user experience, we ha ...

Problem with Vue.js run serve after installation

Recently, I set up Vue on my terminal using the following command: sudo npm install -g @vue/cli Following that, I created a new project, navigated to the folder, and attempted to run the server with the commands: vue create frontend cd frontend npm run se ...

What is the best way to create a button that will trigger a modal window to display a message?

I am looking to create a button that will open a modal window displaying a message. However, when I tried to add a label and viewed the page, the desired window appeared on top of the rest of the content. But unfortunately, clicking the button did not prod ...

Unable to modify the styles of nested Material UI components

I am currently customizing the styles of the card and cardContent components in material ui. I have implemented them within functional components and am facing an issue with overriding the root style of each component. Specifically, I am struggling to modi ...

Jquery allows for the toggling of multiple checkboxes

I have a group of check-boxes that I would like to toggle their content when checked. Currently, I am using jQuery to achieve this functionality, but I am searching for a way to optimize my code so that I do not need to write a separate function for each ...