What is the best way to properly store an axios request in the Vuex store in Vue.js?

I am exploring the idea of creating a dynamic sidebar with links fetched from an API. The theme I am currently working with can be found here:

One interesting feature in this theme is the charts link, which displays a list of children in the sidebar.

My goal is to utilize an API request, let's say for charts, and dynamically generate each child element (check out charts.js) for every item returned by the API.

In the code snippet below, you'll notice that the data objects are currently hardcoded. My intention is to eliminate this hardcoding and use a for loop to dynamically create each child based on the elements received in the API request body.

/store/modules/menu/index.js

[Code block for /store/modules/menu/index.js]

/store/modules/menu/charts.js

[Code block for /store/modules/menu/charts.js]

sidebar.vue

[Code block for sidebar.vue]

I seem to be stuck on this implementation. Any tips or guidance would be greatly appreciated.

Update:

Below is an example of the API response I am dealing with:

[
    {
        "id": 1,
        "name": "test1",
        "os": "windows",
        "url": "https://test.com"
    },
    {
        "id": 2,
        "name": "test2",
        "os": "ios",
        "url": "https://test.com"
    },
    {
        "id": 1,
        "name": "test3",
        "os": "windows",
        "url": "https://test.com"
    }
]

Answer №1

  1. Start by duplicating the routes of charts within the store

    const state = {
      chartsRoutes: []
    }
    
  2. Add a computed property to the component

    computed: {
      chartsRoutes () {
        return this.$store.state.chartsRoutes
      }
    }
    
  3. Utilize v-for to display the chartsRoutes as router-links in the component

  4. Develop a mutation to update both the store and router

    // Import the router
    const mutations = {
      'update-charts-routes': function (state, payload) {
        const { chartsRoutes } = payload
        state.chartsRoutes = chartsRoutes.map(r => {
          return {
            path: '/your/custom/path/according/to/response'
            // other parameters
          }
        })
        router.addRoutes(state.chartsRoutes)
      }
    }
    
  5. Create an action item

    const actions = {
      'reload-charts': function ({commit, dispatch}, data) {
        return new Promise((resolve, reject) => {
          const r = {
            method: 'get',
            url: data.url,
            // add more options like headers or authentication
          }
          axios.request(r)
            .then(resp => {
              commit('update-charts-routes', { chartsRoutes: resp.data })
              resolve()
            })
            .catch(err => {
              // handle errors
              reject(err)
            })
          }
        }
      }
    }
    
  6. Trigger the action

    this.$store.dispatch('reload-charts', { url: 'http://some.host/path/to/url' })
      .then(() => {
        // perform additional tasks
      })
    

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

Passing props to a wrapped component when utilizing a higher order component in React

While exploring the react documentation, I came across a section on Higher-Order Components that included an example of logging props for a specific component. function logProps(WrappedComponent) { return class extends React.Component { componentWillR ...

Guide to incorporating WebElement scrolling in Selenium using Java?

I need to implement a scroll function for a table on my webpage rather than scrolling the entire page, so using window.scrollBy is not an option. After attempting to find the container responsible for the scroll functionality in the DOM (with no luck), I ...

The JQuery Slide feature seems to be malfunctioning when handling data retrieved from the database

I have set up a database with two tables, each containing three rows and connected by ID. The data in table_1 (questions) is linked to the corresponding responses in table_2 (answers) through this linkage. Recently, I attempted to incorporate a SLIDEUP/SL ...

Enhancing mongoose find queries in Node.js with dynamic conditions using both AND and OR operators simultaneously

I've been experimenting with adding dynamic conditions using the Mongoose library. var and_condition = { $and: [] }; var or_condition = { $or: [] }; and_condition.$and.push ({ "doc_no" : /first/i }) or_condition.$or.push ({ "doc_type" : /third/i } ...

My goal is to retrieve the first value in the first table cell after successfully logging into

Snippet of HTML Code: <table id="ctl00_pagecontent_ctl01" class="ui-jqgrid-btable" tabindex="1" role="grid" aria-multiselectable="false" aria-labelledby="gbox_ctl00_pagecontent_ctl01" style="width: 1053px;" cellspacing="0" cellpadding="0" border="0"& ...

Receiving HTTP POST data using Classic ASP script

I'm currently working on a project and have come across an area where I am facing some challenges. Despite my best efforts, I haven't been able to find a solution using Google. In my ASP web application, I've added an HTML canvas that I nee ...

Interact with a React dropdown using SeleniumBase

I am having trouble testing a dropdown on a webpage I built with React and the Ant Design framework. I am attempting to use SeleniumBase or Selenium Webdriver for the task. The dropdown in question can be viewed here: https://ant.design/components/select/ ...

Switching the default image using jQuery upon click event

When I click on the image, I want to see a new image appear for just one second before returning to the default. I tried using setTimeout() function, but even after one second, I still see the same pressed.svg image. Here is my complete code: <html> ...

I've noticed that the NextJs router appears to be significantly slower in comparison to React

I currently have a website that is built in both React Js and Next Js. The issue I am currently encountering is that the router in NextJs is noticeably slower compared to react-router-dom. It takes almost 2-3 seconds to change the route. To experience th ...

What is the process of adding a newly uploaded file to an existing list of files using Vue?

I have implemented a file uploader that can accept a single CSV file and successfully POST it to the server using axios. However, I am facing difficulty in allowing users to upload multiple CSV files at different times, and have them added to the list of u ...

Whenever I try to include something within the `componentWillUnmount` function,

I'm currently learning React on my own. I've been trying to save session data in my componentWillUnmount method. However, when I add code inside componentWillUnmount, nothing seems to happen. I tried debugging by adding console logs and debugger ...

Display the elements of a div at a reduced size of 25% from its original dimensions

I'm currently developing a JavaScript-based iOS simulator that allows users to view their created content on an iPhone and iPad. This involves using AJAX to load the content/page into the simulator, but one issue is that the simulator isn't life- ...

I'm encountering an unfamiliar error within my Discord.js bot, and I'm unsure of both its cause and the appropriate solution. Additionally, I'm unsure which specific file

I'm facing a recurring issue with my bot terminal. It's been causing me trouble for the past four days, functioning intermittently without any pattern. I'm struggling to track down the specific file where this error is originating from. Any ...

Struggling with updating an array using React's setState

My issue lies with setState not properly updating my todoItems array. After reviewing similar posts on this forum, I made changes to my addTodoItem() function by utilizing a function and the spread operator. While a new item is successfully added to the ar ...

Tips for implementing authentication in Vue.js with Azure Active Directory integration

My Vuejs Application needs to be authenticated using a client secret in Azure AD, but I'm having trouble finding any resources on how to do this. ...

In a React component, what is the significance of "this" in relation to accessing state values (this.state...)?

I encountered a challenging issue with the usage of the this keyword while setting a state within an ajax call. It seems like I may have misunderstood something about how React components operate. How should I properly utilize the this keyword in this sp ...

Assigning input array values with jQuery

I'm currently working on incorporating HTML input arrays. <input type="text" name="firstName[]" id="firstName[]"> I also need to populate another form that looks like this: <form id="tempForm"> <input type="text" name="userName" i ...

Using JavaScript and jQuery to make calls to the Web API

I am struggling with Java-script callback due to lack of experience. Can anyone provide assistance in resolving the issues I am facing with the code? My goal is to perform a callback from a .json file and search it by ID. While I can display all customers, ...

Delete the file containing Mongoose references

I'm facing an issue with deleting questions when a survey is deleted in the Survey model. Even after deleting the survey, the question remains intact in the database. Survey Schema: let surveyModel = mongoose.Schema( { Title: String, T ...

Problem with autocomplete functionality in Angular Material's md-contact-chips

Having some trouble with the autocompletion feature of md-contact-chips. I want to capture the $query as soon as someone starts typing. HTML <md-contact-chips ng-model="members" md-contacts="querySearch($query)" md-contact-name="fullname" ...