Having trouble with Laravel Vue.js mixins not receiving function responses?

I'm currently working with Laravel 5.8 and Vue.js. I've created a function for handling post/get requests in a more generalized way. However, I'm facing an issue where I am not receiving the expected response from the mixins function. Below is a snippet of my code:

TestComponent.vue

import GeneralMixin from '../mixins.js';
export default {
    mixins: [GeneralMixin],
    methods:{
        login: function (e) {
            let response;
            response = this.testMixin();
            console.log(response);
        }
    }
}

mixin.js

export default {
    methods: {
        testMixin: function () {
            url = '/test';
            axios.post(url).then(function(response, status, request) {  
                return response;
            });
        }
    }
}

The result in the console is undefined

I'm struggling to get the response from the testMixin() function. Any help would be greatly appreciated!

Answer №1

In order to retrieve the response from the mixin, it is essential to wrap the axios request in a promise:

return new Promise((resolve, reject) => {
  axios.post(url).then(function(response, status, request) {  
     return resolve(response)
  })
})

If you wish to utilize this response in another function, you can do so by:

login: function (e) {
  this.textMixin().then((response) => {
    console.log(response)
  })
}

However, it is discouraged to solely return the response from the promise as it creates an anti-pattern. Instead, consider returning the entire axios request for internal consumption:

return axios.post(url)

This way, you have more control over handling the response:

login: function(e) {
    this.testMixin().then((response) => {
       console.log(response)
    }).catch((error) => {
       console.log(error.response.data)
    })
}

Answer №2

To ensure successful execution, ensure that the promise is returned by following the example provided below

Implement it in your mixin

return axios.post(url);

Next, utilize it in your component as shown below.

this.invokeMixin().then((response) => {
       console.log(response)
    }).catch((error) => {
       console.log(error.response.data)
    })

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

Discovering Vue.js Event Handling: How to Identify If a Key Is Pressed While the Mouse Hovers over a Specific Element?

I am currently developing a Vue.js 3 multi-item selection feature. Each item is displayed as a <div> element with a checkbox inside. One functionality I am trying to add requires detecting when the Shift key is held down while the mouse hovers over ...

What is the best way to revert the Highcharts bar color back to its default color?

I am currently working with Highcharts version 4.1.10 In my bar chart, I have implemented a feature where the color of the bar changes when its value exceeds a certain threshold. //This function is called at regular intervals by a timeout function myTime ...

Error: OpenAI's transcription API has encountered a bad request issue

const FormData = require('form-data'); const data = new FormData(); console.log('buffer: ', buffer); console.log('typeof buffer: ', typeof buffer); const filename = new Date().getTime().toString() + '.w ...

Should V-for be used within V-if in Vue.js for optimal coding practices?

During a recent project, we utilized the following code: <template> <div id="app"> <button @click="fetch">Fetch numbers</button> <div v-if="!getNumbers.length">Waiting for numbers...</div> <div v-if=" ...

Extract content from whole webpage including HTML, CSS, and JavaScript

Currently I am working on developing a webpage version control backup/log system. The goal is to automatically save a static copy of the webpage, including all its CSS and JavaScript files, whenever there are any changes made. I have already figured out h ...

Utilize data obtained from an ajax request located in a separate file, then apply it within a local function

Seeking assistance in navigating me towards the right path or identifying my errors. Pardon if my explanation is unclear, please be gentle! Currently, I am engaged in developing a function that executes an ajax call with a dynamically generated URL. The o ...

Transform a protractor screenshot into a PDF file

I'm currently working on a small Protractor code that captures screenshots, but my goal is to save these screenshots as PDF files. Below you can find the code snippet I have written. await browser.get(url); const img = await browser.takeScreenshot(); ...

Ubuntu is experiencing a DNS problem. While the URL request works perfectly on MacOSX, it is unsuccessful on Ubuntu

A custom nodeJS script has been developed to utilize the require('request').post() method. The script executes successfully on MacOSX (Travis), however encounters issues on Ubuntu (Travis). To troubleshoot, experimentation with NodeJS 'https ...

Exploring Vuex Mutations alongside Airbnb's eslint rules

In my Vuejs project (utilizing Vue-cli), I have integrated Airbnb Eslint which enforces various rules, including no-param-reassign. To manage the state (using Vuex), mutations/actions are essential: Rule Conflict mutations: { increase: (state) => ...

VueJs: Finding the corresponding value of a data object

Is there a way to extract data from an object in Vue? This is the format of my data: datasets: [{ text:"Cars", value: "[1,2,3]" }, { text:"Trains", value: "[1,4,10] } ] When I receive information from route props like this: this.selectedText= this ...

Code error: JSON unexpected token "&" encountered

When utilizing the $http.get() method for a GET request, the response is in JSON format, but some characters are HTML encoded. For example, the double quote " is encoded as &quot;. { &quot;description&quot;:&quot;invalid&quot;, ...

What is the best way to consistently and frequently invoke a REST API in Angular 8 using RxJS?

I have developed a REST API that retrieves a list of values. My goal is to immediately invoke this API to fetch values and store them in a component's member variable. Subsequently, I plan to refresh the data every five minutes. Upon conducting some ...

Issues arise when attempting to smoothly scroll to an anchor point in a webpage

While working on my website, I have encountered a challenge. The issue arises when dealing with multiple div items. Upon scrolling slightly, the entire page focuses on the div with a height of 100vh, which works perfectly fine. However, my attempts to ...

Building custom components in Vue.js/NuxtJS can be a breeze when using a default design that can be easily customized through a JSON configuration

Currently, I am in the process of developing a NuxtJS website where the pages and components can either have a generic design by default or be customizable based on client specifications provided in the URL. The URL structure is as follows: http://localh ...

"Implementing a feature in React JS react-table to dynamically add a new column when a

I'm struggling to add a new column to react-table when a button is clicked. Even after re-rendering the table with a flag, I can't seem to add the new column. Can anyone suggest where I might be going wrong? Here's the link to the executable ...

The input type '{}' does not match the expected type 'Readonly<IIdeasContainerProps>'. The property '...' is not found in the type '{}'

Having recently started using TypeScript, I'm encountering some issues when attempting to execute this code snippet. Error The error message reads as follows: Failed to compile 13,8): Type '{}' is not assignable to type 'Readonly &l ...

Unable to transfer Base64 encoded data to C# through AJAX

I'm facing an issue where a base64 string I send through ajax to an aspx page with C# code behind always arrives empty. Despite other form fields posting successfully, this particular string is not making it through. The base64 string in question app ...

Learn how to use JavaScript to parse binary files

Is there a way to interpret this binary data below? Binary2 { sub_type: 0, buffer: Buffer(16) [ 12, 15, 64, 88, 174, 93, 16, 250, 162, 5, 122, 223, 16, 98, 207, 68 ], position: 16 } I've attempted different methods like using ...

Linking promises together ensures that they always resolve with a result

My understanding of how to chain promises is still not completely solid. What I am trying to achieve is as follows: I have a promise that can either resolve or reject. The following code checks for this and continues if the promise resolves, or stops if i ...

Tips for updating and transferring a variable within a callback function

I have implemented a function using the SoundCloud API that retrieves a song URL, obtains the associated sound ID from the API, and then passes that ID to a callback for streaming purposes and updating the page. The data is successfully retrieved from the ...