Leveraging the power of axios.all for dynamic operations

Is there a way to efficiently reuse the same Vue-component for both editing and creating new users?

While working with vue-router, I have implemented a beforeRouteEnter method to fetch data via API. Depending on whether an ID is set in the URL parameter, I determine if it's for updating an existing user (edit) or creating a new one.

This is my current approach:

beforeRouteEnter (to, _from, next) {
        if (to.params.id) {
            axios
            .all ([
                axios.get ('/api/user/' + to.params.id),
                axios.get ('/api/states/users')
            ]).then (axios.spread ((userRes, statesRes) => {
                    next ((vm) => {
                        vm.user = userRes.data.data;
                        vm.states = statesRes.data.data;
                        vm.create = false;
                    });
                })
            );
        }
        else {
            axios
            .all ([
                axios.get ('/api/states/users')
            ]).then (axios.spread ((statesRes) => {
                    next ((vm) => {
                        vm.states = statesRes.data.data;
                    });
                })
            );
        }
    },

I acknowledge that this implementation may not be the most elegant solution. One idea I had was to store the URL in an array and push '/api/user/' + to.params.id) to that array when to.params.id is not empty. However, I am unsure about how to handle the axios.spread part in this scenario.

Therefore, my question remains: How can I optimize my code for better performance and readability?

Answer №1

One approach to streamline the process is by constructing the promise array prior to utilizing axios.all. In the context of ES6, you have the option to forgo utilizing axios.spread in favor of employing array destructuring.

Consider the following implementation:

beforeRouteEnter(to, _from, next) {
    const promises = [
        axios.get('/api/states/users')
    ];

    if (to.params.id) {
        promises.push(axios.get(`/api/user/${to.params.id}`));
    }

    axios.all(promises)
        .then(([statesRes, userRes]) => {
            next((vm) => {
                vm.states = statesRes.data.data;
                if (userRes) {
                    vm.user = userRes.data.data;
                    vm.create = 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

What methods can be used to circumvent test coverage for external or dependency Vue components?

We're facing an issue with our two Vue3 projects. Project 1 relies on components imported from Project 2 as dependencies. Within Project 1, MyComponent.vue: <template> <Project2Modal> Some html here </Project2Modal> </template& ...

Tips for utilizing variables as the initial value of a JSON Object

Here is a JSON configuration example: { "Users" : { "182723618273612" : 15, "AddedUser" : 1 } } I have generated this field using a JavaScript function, but now I want to change the name of "AddedUser" ...

Retrieve the Checked Value of a Checkbox Using Ajax Post in MVC

Can anyone provide assistance? This is the code I am working with: Index.cshtml <!DOCTYPE html> <html> <head> <title>jQuery With Example</title> @Scripts.Render("~/bundles/jquery") <script type="text/javascri ...

Limit the selection to just one element in a v-for loop in VueJS

I am utilizing Vue v2 My goal is to change only the properties of the selected element. Specifically, when the response is marked after clicking, it should switch to red color with a text that reads 'Unmark'. Conversely, if the button is clicked ...

Controller encountering JSON null data

I am currently working on a feature that allows users to send multiple email/SMS messages by selecting checkboxes. However, I am facing an issue where the data is not being passed correctly from my JavaScript function to the action method - all the data sh ...

Tips on accessing close autoComplete/TextField title in AppBar

Looking to add a search bar and login button in the AppBar, where the search Bar is positioned close to the title. The desired order for the AppBar components should be as follows: Title SearchBox LoginButton How can this be achieved? Below is th ...

Integrate React tags with Redux form to ensure the values are transmitted as an array within the payload

I am currently working on a redux-form that contains a component for tags. I am struggling to figure out how to retrieve the tag values in an array as a payload. Any help would be greatly appreciated. Below is the code snippet for the tags component: ...

Creating a water vessel design using CSS

Despite going through the JS tutorial, I still struggle with it and need some assistance. I believe using a jsfiddle would be helpful. I am attempting to use JS to create a small box that changes color from green to empty based on the fullness of a "wate ...

What is the proper way to use AJAX for sending data through a POST request?

Check out my Fiddle Currently, I am in the process of learning AJAX through a tutorial and so far, I have managed to retrieve the desired data and display it on the DOM quite effortlessly. However, I have encountered some difficulties when attempting to ...

Substitute the symbol combination (][) with a comma within Node.js

Currently, I am utilizing Node JS along with the replace-in-file library for my project. Within a specific file named functions.js, I have implemented various functions. Furthermore, in another file named index.js, I have added code to call these functio ...

The detected coordinates are offset from the location of the mouse click

Seeking guidance: I need advice on an issue that arises when clicking on the second tooth from right to left, causing the upper teeth to be colored instead: https://i.sstatic.net/czzmc.png Below is a step-by-step explanation of what the code does: 1) T ...

Retrieve the size of an element without having to wait for the browser to "recalculate style"

I am currently focused on optimizing the performance of some code that heavily relies on graphics. One of the main issues I am encountering is the delay in obtaining the dimensions of a specific div element. Most of the time, this process runs smoothly, bu ...

Why is the result of this specific JavaScript code a string?

let x = 2, y = x = typeof y; console.log(x); // >> 'string' Could you explain why the value of x ends up being a string in this code snippet? ...

What is the process for embedding JQuery within the <body> tags in Joomla 3.1?

I inserted the following code into my default.php file in Joomla 3.1. <?php JHtml::_('jquery.framework'); JFactory::getDocument()->addScript(JURI::root().'template/mytemplate/js/jquery.min.js'); ?> However, this code only pl ...

Can you explain the variation between a standard javascript integer and one obtained from jquery.val()?

Utilizing a script known as countUp.js, I am able to increment an integer in a visually appealing manner until it reaches the desired value. This is how I have implemented the code: HTML: <h2 id="countUp-1">2500</h2> JS var theval = 5000; va ...

Display HTML content using JavaScript only when a checkbox is selected

Currently, I am updating an HTML form to show additional subsets of questions based on the selection of a "parent" checkbox. The current implementation works well, but I am wondering if there is a more efficient way to achieve this without having to rewrit ...

A declaration file for the 'vuelidate' module could not be located

When I was following the installation instructions for Vuelidate in Vuejs (), I encountered a warning message at this line: import Vuelidate from 'vuelidate' The warning states: There seems to be an issue with finding a declaration file for t ...

Tips for passing down props or all the properties of an object to create a dynamic component

I am facing an issue with a v-for loop in my project. The loop is supposed to iterate through objects in a list of todos fetched from the backend. These objects are then passed down to a child component, which displays each todo individually. However, I ha ...

Ways to identify when the scroll bar reaches the end of the modal dialog box

I have been working on a modal that should display an alert when the scrollbar reaches the bottom. Despite my efforts to research a solution, I am struggling to detect this specific event within the modal. The desired outcome is for an alert to pop up once ...

Are we retrieving multiple APIs the right way?

Looking for some guidance on fetching two APIs in React. I have created two functions to handle this task and called them simultaneously within another function. Should I stick with this approach or move the API calls to componentDidMount? Additionally, I& ...