Having difficulties integrating a login solution due to an error saying "eslint Promise executor functions should not be async no-async-promise-executor"

I'm currently working on integrating a login solution into my Vue app using the JWT Authentication plugin.

While I have a test solution that is functional, I'm facing an issue in my main branch where the eslint version seems to be causing an error with "Promise executor functions should not be async no-async-promise-executor".

The code within my 'store' and under my actions looks like this:

login({ commit }, credentials){
  return new Promise(async (resolve, reject) => {
    try {
      const { data }  = await axios.post(`https://mywebsite.com/wp-json/jwt-auth/v1/token`, credentials)
      commit('SET_USER', data)
      resolve(data)
    }catch(e){
      reject(e)
    }
  })
},
validate({ state }) {
  return axios({
    url: `https://mywebsite.com/wp-json/jwt-auth/v1/token/validate`, 
    method: 'post',
    headers: {
      'Authorization': `Bearer ${state.user.token}`
    }
  })
},

I'm unsure how to refactor this code to resolve the error. Any suggestions?

Answer №1

It appears that there may be some confusion regarding async/await usage. When utilizing async/await, there is no need to wrap it within a Promise object. Simply include the async keyword in the method and utilize await appropriately.

var app = new App({
    methods: {
        async authenticate({ commit }, credentials) {
            try {
                const { data } = await axios.post(
                    `https://myapi.com/authenticate`,
                    credentials
                );
                commit("SET_USER", data);
            } catch (error) {
                console.log(error);
            }
        },
        checkValidity({ state }) {
            return axios({
                url: `https://myapi.com/check-validity`,
                method: "post",
                headers: {
                    Authorization: `Bearer ${state.user.token}`,
                },
            });
        },
    },
});

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

Creating DOM elements upon successful completion of an AJAX request with jQuery has never been easier. Here's a

I'm currently working on a project where I am dynamically creating a list of checkboxes using jQuery's $.ajax method. function load() { $.ajax({ type: "POST", url: "*************", data: "************ ...

Is there a way to restrict access to my website to only be opened in the Chrome browser?

Is there a way to prevent my web application from loading when the link is opened in browsers other than Chrome? Can this be achieved using Javascript or Java? I want to restrict the usage of my web application to only Chrome. Any assistance would be appre ...

I wish to trigger the function when the button with the ID "add_city" is clicked instead of it being activated upon pressing the Enter key as it currently is

Is it possible to trigger the function by clicking a button with the id "add_city", rather than just pressing Enter? function createCity(stateId, newCity, event) { if(event.keyCode == 13 || $(this).attr('id') === 'add_city') { i ...

Vue - Seamlessly Editing and Creating Content Together

When using Laravel, I am attempting to pass data to a Vue component. Depending on whether the user enters the component through an edit URL or a create URL, we send either an array of data or null. Here is an example of how this process works: Blade view ...

What is the procedure for defining the secret code for a private key in saml2-js?

I need to implement a key/cert with a passphrase in my project that's currently using saml2-js. I have already set up everything but encountering a bad decrypt error without the passphrase. Is there a way to incorporate this passphrase? Below are the ...

Having trouble with reactjs and typescript? Getting the error message that says "Type 'string' is not assignable to type 'never'"?

When trying to setState with componentDidMount after an axios request is completed, you may encounter the error message Type 'string' is not assignable to type 'never'. Below is the code snippet: import * as React from 'react&apos ...

Having trouble with the Lottie player not loading a JSON object or string into the src attribute?

Having an issue with my Vue.js project where I am using lottie player integrated with lottie-interactivity. When I try to pass a json string/object directly instead of a .json file link to the lottie-player, the animation doesn't seem to load. Any sug ...

Testing an API request using Jasmine for unit testing

I am currently working on writing unit tests for the website I'm developing at my job. One thing I'm struggling with is how to effectively test an API call within one of my Vue components. Let's say I have the following code snippet in my V ...

Passing props to another component using the <Link> element in React Router

I'm working on a project where I need to display search results using an array. When a user clicks on an item, I want to pass that item as props rather than as parameters. Below is the code snippet: { this.props.results.map((result) => { ...

Issue with Bootstrap 3 Modal: Missing Title and Input Labels

I'm currently working on customizing a bootstrap template for my friend's church website. My goal is to create a simple web presence for them, and I am in the process of setting up a contact form. I want this form to appear as a modal where users ...

Verifying conditions in an AJAX-based upload system using JavaScript

Recently, I was working on implementing a JavaScript/AJAX upload system with a progress indicator based on a tutorial. The process went smoothly, and I even managed to include a CSS progress bar for visual representation. However, I encountered a hurdle th ...

Sliding out list elements with jQuery ladder effect

I'm stuck on a seemingly simple task and need some guidance. facepalm. Currently, my site at this link has a menu list item issue where they all come out from the left side after the picture loads. I want them to slide out one by one, starting from t ...

Expecting a volumetric result can be deceiving when dealing with objects that have three flat

The problem at hand: When subtracting a cube from a sphere, an interesting result occurs where the z axis maintains its volume while the y and x axes create flat disks. This peculiar outcome is puzzling to me as I utilize the typical subtraction method wi ...

Let's compare the usage of JavaScript's toUTCString() method with the concept of UTC date

When I fetch the expiry date time in UTC from the Authentication API along with a token, I use the npm jwt-decode package to extract the information. private setToken(value: string) { this._token = value; var decoded = jwt_decode(value); this._ ...

Utilize jQuery to generate an HTML table from a JSON array with rows (Issue: undefined error)

please add an image description hereI am attempting to populate the data in an HTML table using jQuery, but all columns are showing as undefined errors HTML: <table id="example" class="table table-striped" style="width:100%&quo ...

Java's equivalent to the return function in JavaScript

Currently, I am in the process of adapting three.js into Java while also incorporating my own modifications and enhancements. One specific challenge I am facing involves determining the best approach for managing reflection within the code. As part of thi ...

Locating numerous words within a given string

In my quest to identify specific words within a comma-separated log, I have encountered an issue. The current code snippet effectively locates individual words, but struggles to find all three words together in the log. $log = "Left Side Turn, Left Side ...

What could be the reason for encountering the error "logic is not defined" in this particular

Having recently started learning JS and React, I encountered an error that stated: "logic is not defined". class Keyboard extends React.Component { logic() { return false; } render() { return ( <div> <h1>{log ...

Having trouble converting my form data into an array for table display

My website has a form for entering dummy patient information, with a table to display the submitted data. However, I'm facing an issue where the data is not being stored in the array when the user clicks the "Add Patient" button. Upon checking the arr ...

JavaScript: Discovering the art of "utilizing RESTful APIs"

After several years of coding in JS, I am now expanding my knowledge. I have noticed many job postings asking for familiarity with REST APIs and experience consuming RESTful services. I have a solid grasp on AJAX basics using both vanilla JS and jQuery. I ...