Tips for receiving an ajax response in Vue.js 2

Here is the code snippet I am working with:

<template>
    <a href="javascript:" class="btn btn-block btn-success" @click="addFavoriteStore($event)">
        <span class="fa fa-heart"></span>&nbsp;Favorite
    </a>
</template>

<script>
    export default{
        props:['idStore'],
        mounted(){
            this.checkFavoriteStore()
        }, 
        methods:{
            addFavoriteStore(event){
                alert('toast');
                event.target.disabled = true;
                const payload= {id_store: this.idStore};
                this.$store.dispatch('addFavoriteStore', payload);
                setTimeout(function () {
                    location.reload(true);
                }, 1500);
            },
            checkFavoriteStore(){
                const payload= {id_store: this.idStore};
                this.$store.dispatch('checkFavoriteStore', payload);
                setTimeout(function () {
                   location.reload(true);
                }, 1500); 
                // Obtain response here  
            }
        }
    }
</script>

When running the script, it will first invoke the checkFavoriteStore method.

The checkFavoriteStore method triggers an action on the Vuex store.

The results of the action will yield a response.

How can I retrieve this response?

UPDATE

My Vuex store action appears as follows:

import { set } from 'vue'
import favorite from '../../api/favorite'
import * as types from '../mutation-types'

// Actions
const actions = {
    checkFavoriteStore ({ dispatch,commit,state },payload)
    {
        favorite.checkFavorite(payload,
            data => {
                commit(types.CHECK_FAVORITE_SUCCESS)
            },
            errors => {
                commit(types.CHECK_FAVORITE_FAILURE)
                console.log(errors)
            }
        )
    }
}

// Mutations
const mutations = {
    [types.CHECK_FAVORITE_SUCCESS] (state){
        state.addStatus = 'success'
    },
    [types.CHECK_FAVORITE_FAILURE] (state){
        state.addStatus = 'failure'
    }
}

export default {
    actions,
    mutations
}

And the API structure is outlined below:

import Vue from 'vue'
import Resource from 'vue-resource'

Vue.use(Resource)

export default {

    // Check if favorite exists in the API or not
    checkFavorite (favorite, cb, ecb = null ) {
        Vue.http.post(window.Laravel.baseUrl+'/member/store/favorite/check-favorite', favorite)
            .then(
            (resp) => cb(resp.data),
            (resp) => ecb(resp.data)
        );
    }
}

Answer №1

When retrieving a result, it is recommended to store the call in a variable like so:

  var response = this.$store.dispatch('checkFavoriteStore', payload);

You can then access the response using the variable response. The events should return the data back to you.

FURTHER INQUIRY:

I have a small question regarding this scenario.

If you are passing the store ID as a prop to the component, wouldn't it be beneficial to also pass another prop indicating if the store has already been liked? This way, you can fetch this data from the database and avoid the need for an additional check after the component loads. For example:

  <favorite-button :storeid="23" :favorited="true"></favorite-button>

Utilizing the favorited property to adjust the button's state, eliminating the need for the checkFavoriteStore call and reducing the number of HTTP requests required.

I might not be aware of your code or its functionality, but this is just a suggestion?

AFTER ADDITIONAL INFORMATION UPDATE:

Please consider updating your HTTP request to:

Vue.$http.post(window.Laravel.baseUrl+'/member/store/favorite/check-favorite', favorite)
  .then((response) => {
      console.log('success')
      console.log(response.data);
    return response.data;
  }, (response) => {
       console.log('success');
        console.log(response);
    return response;
  });

I have included console logs to provide visibility into the process. Let's see if this improves the situation?

Additionally, try adding a return statement beforehand, as it must return to the original caller:

 return favorite.checkFavorite(payload,
        data => {
            commit(types.CHECK_FAVORITE_SUCCESS)
        },
        errors => {
            commit(types.CHECK_FAVORITE_FAILURE)
            console.log(errors)
        }
    )

Furthermore, do you require such complexity for a simple check like this? Perhaps consider passing the button's state as a prop (as mentioned above) and handling the 'isFavorited' logic within the component itself, avoiding the need for a store in this instance??

UPDATE 2:

If you require a different approach with promises, consider the following::

Vue.$http.post(window.Laravel.baseUrl+'/member/store/favorite/check-favorite', favorite)
  .then((response) => {
      console.log('success')
      resolve(response.data);// replace the return with resolve?
  }, (response) => {
       console.log('success');
        console.log(response);
    reject(response.data);// replace the return with reject?
  });

This adjustment may address the issue at hand??

Answer №2

Here is a creative solution that eliminates the need for a store, offering a convenient alternative:

PHP Page:

    <favorite-button 
        :storeid="{{$storeid}}" 
        :favorited="{{$isFavorited}}"
        :url="{{route('check-favorite')}}"
    ></favorite-button>

    <script>
        (function(){
            import favoriteButton from 'favorite-button';
            new Vue({
                el : '#app',
                components : {
                    favoriteButton
                }
            });
        })();
    </script>

Next, let's look at the component:

    <style lang="sass">
        .heart {
            color: grey;
            &.is-favorited {
                color: red;
            }
        }
    </style>
    <template>
        <button class="btn btn-block btn-success" @click.prevent="updateFavorited($event)">
            <span class="heart" :class="{'is-favorited' : this.favorited }">&heart;</span>&nbsp;<span :text="{this.favoriteText}"></span>
        </button>
    </template>
    <script>
        import axios from 'axios';
        export default{
            props : {
                storeid : {
                    type: Number,
                    required : true,
                    default : () => {}
                },
                favorited : {
                    type: Boolean,
                    required : false,
                    default : false
                },
                url : {
                    type: String,
                    required : true
                }
            },
            computed : {
                favoriteText : function(){
                    return (this.favorited) ? 'Unfavorite' : 'Favorite';
                }
            },
            methods:{
                updateFavorited(event){
                    //-- Update the database - if false, update to true; if true, set to false
                    axios.post(this.url, this.storeid)
                        .then(response => {
                            //-- If successful, update the visual button
                            this.favorited = response.data.favorited
                        })
                        .catch(error => {
                            console.log('error');
                            console.log(error);
                            this.favorited = response.data.favorited
                    });

                }
            }
        }


    </script>

Upon initial page load, pass the store id, current favorite status, and click action URL.

When a user clicks the button, it will update the DB and adjust the text and heart color accordingly.

Consider this as another innovative solution to address any challenges you may be facing!

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

Whenever I relocate the button's position within the Bootstrap framework, it seems to end up in a completely different

body <div class="container" style="margin-top: 70px;"> <div class="formlogin bg-light bg-gradient shadow-lg p-3 mb-5 bg-body rounded col-8"> <p id="signText"> Signin Fo ...

Interactive Vue.js canvases that adapt and respond to various

I am currently working on adjusting my canvas to fit within its container in a Vue component. When I call resizeCanvas() in the mounted hook, I notice that the container's height and width are both 0. How can I create a canvas that dynamically fits it ...

Divide the array of words into segments based on the maximum character limit

I am looking for a way to divide an array of words into chunks based on a maximum number of characters: const maxChar = 50 const arrOfWords =['Emma','Woodhouse,','handsome,','clever,','and','rich,&apo ...

Can we store multiple Foreign Keys in Laravel in order to display numerous items from different tables in a Package Items table within Quasar 1 Laravel 2 framework?

My goal is to create an Ecommerce website where each product can belong to multiple categories. I have a form called PackageItem table (similar to PRODUCT) and when I select an item, it retrieves the name from the Item table (similar to CATEGORIES). http ...

Would you be able to clarify why the run() function is giving me an error when I try to return {1,3}, but it works fine when I return {a,b} in

I'm really confused as to why the return {1,3} in the run() function is throwing an error when it works just fine for return {a,b} in the fun() function function fun(){ let a = 10; let b = 20; return {a, b}; } ...

List items are loaded dynamically in an unordered fashion

I have been working on a jquery slider using flickerplate. Below is the code that works when the values are hardcoded: <div class="flicker-example"> <ul> <li data-background="lib/flicker-1.jpg"> <div class ...

Syntax error occurs while attempting to render the return statement in a React Component

Just starting out with React and encountering a syntax issue that has me stumped. I'm working on a React Component and I thought I had the opening/closing { & }'s correct, but clearly there's something missing based on the error message it&a ...

Using react-input-mask together with a child component in React is not compatible

I've been exploring ways to mask a Material UI TextField, and after researching some solutions online, I came across this code snippet: <InputMask mask="(0)999 999 99 99" value={phone} disabled={false} ...

Sharing data between React JS components Passing information between different components in React JS

My NavBar.js component contains login information for the logged-in user. It displays "Welcome" along with the user details when the user is logged in. Now, I want to replicate this functionality in the ProductList.js component so that when a user posts a ...

configure Jquery AJAX settings using a JavaScript object

While working with a jQuery AJAX call, I encountered an issue where defining the ajax properties 'from scratch' worked perfectly fine. However, when setting the same values in a JavaScript object and then using that object to define the ajax requ ...

Troubleshooting: jQuery ajax form is not functioning as expected

After attempting various methods to create a basic jQuery Ajax form, I am puzzled as to why it is not submitting or displaying any notifications. Below is the code I have been working with: Javascript ... <script type="text/javascript" src="assets/js ...

"webpack" compared to "webpack --watch" produces varying results in terms of output

My project is built on top of this setup: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html Running webpack compiles a bundle that functions correctly in the browser. However, running webpack --watch to recompile on file changes resul ...

Preventing mouse controls from moving the cube: a gift/page2 tutorial

(gift/page2) in this snippet: You can observe a demonstration of a red cube rotating on the web page. However, my goal is to prevent the cube from being manipulated by the mouse or fingers on an iPad. I want the cube to remain stationary in its position. ...

Pairing items in a list using the concept of functional programming

Looking to arrange an array by grouping items together? For example: [1, 1, 0, 1, 0, 1, 0] => [1, 1, 0, 1, 1, 0, 0] OR [1, 1, 0, 1, 0, 1, 0] => [[1, 1], [0], [1, 1], [0, 0]] In this scenario, the goal is to group 1s with a maximum group size of 2 ...

What causes Three.js OBJ conversion to render as mesh successfully but log as undefined?

I'm just getting started with Three.js and I'm experimenting a lot. Although I'm new to Javascript as well, the issue I'm facing seems to be more about variable scoping and callback function protocols than it is about Three.js itself... ...

Tips for simulating a window event in Vue Test Utils while conducting unit tests

I have included 'attachToDocument' in my code, but I am still unable to trigger a keyup event on the window. The versions of my dependencies are: "@vue/test-utils": "^1.0.0-beta.29" "vue": "2.5.18" <template lang="pug"> div h1 123 < ...

Can you include conditional logic within a switch statement?

I've been using if, else if, and else statements in my code but recently switched to switch statements which have made things much simpler. Now I'm wondering if it's possible to add multiple conditions inside a switch statement, similar to i ...

Guide to making a Java Servlet for a specific jQuery.ajax () request?

In one of my files named wfd.proxy.js, I have the following code snippet: if (!WFD) { var WFD = {}; }; if (!WFD.Proxy) { WFD.Proxy = {}; }; WFD.Proxy = { SERVICE_URL : "/delegate/WFD/WFService?", PDF_SERVICE_URL : "/delegate/pdf-exporter?", ...

Tips for displaying specific information using Javascript depending on the input value of an HTML form

I am working on an HTML form that includes a dropdown list with four different names to choose from. window.onload = function(){ document.getElementById("submit").onclick = displaySelectedStudent; } function displaySelectedStu ...

Do not decode HTML content within an iframe; instead, extract the data directly from the HTML source

To expedite execution time, we have made the decision to not display the table in the iframe as it is invisible to the client. However, we still need to update the main page table by copying its contents. The approach we are taking is that the iframe shou ...