Vue component using axios for conditional state toggling

My Vue method/function triggers a state change and toggles text on a button upon click.

pauseTask: function() {
      this.isOpen = !this.isOpen;
      this.pauseButton.text = this.isOpen ? 'Pause' : 'Resume';
},

While it works flawlessly, I now require an axios call to be made each time depending on the state. If this.isOpen is true, then:

axios.post('/item/status/pause',data)
        .then((response) => {
        // handle success
        console.log(response.data);
        if (response.data.success == false) {
            this.errors = [];
            const errorLog = Object.entries(response.data.errors);
            for (var i = errorLog.length - 1; i >= 0; i--) {
                console.log(errorLog[i][1][0]);
                this.errors.push(errorLog[i][1][0]);
            }
        }
    });

and if !this.isOpen then:

axios.post('/item/status/resume',data)
        .then((response) => {
        // handle success
        console.log(response.data);
        if (response.data.success == false) {
            this.errors = [];
            const errorLog = Object.entries(response.data.errors);
            for (var i = errorLog.length - 1; i >= 0; i--) {
                console.log(errorLog[i][1][0]);
                this.errors.push(errorLog[i][1][0]);
            }
        }
    });

Is there a way to achieve this within the existing structure?

Answer №1

To enhance the organization of your code, I recommend creating a separate JavaScript (or TypeScript) file dedicated to communicating with your API. You can then encapsulate all API calls within this file and import it as an 'itemService' or similar module.

For example, within your "pauseTask" function, you could use:

if(this.isOpen) { itemService.pause(item) } else {itemService.resume(item)}

Alternatively, you can set up a watcher for the isOpen property like so:

 watch: {
    isOpen: function (val) {
       if(val) { itemService.pause(item) } else {itemService.resume(item)}
    }

The benefit of using a watcher is that any changes made to the isOpen property will automatically trigger the corresponding API calls.

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

Asynchronous setTimeout for server-side operations

I am currently facing an issue with my web server. Whenever a request is made, the server initiates a phone call, waits for 3 seconds, and then checks if the call is still ongoing. I have utilized setTimeout to achieve this functionality, but it seems to b ...

Leverage variables in the path of your Express.js route

Currently in the process of developing a web application using the MEAN stack and I have a specific scenario in mind: Users should be able to sign up, but then they must also register at least one company. Upon registering a company, the base URL struct ...

Vite deciding to generate its own node_modules directory within the workspace rather than depending on a monorepo

I have organized a monorepo for a fullstack webapp with the directory structure outlined below: . ├── client │ ├── index.html │ ├── package.json │ ├── src │ └── vite.config.ts ├── node_modules ├── p ...

Encountering issues with Monaco Editor's autocomplete functionality in React

I'm facing an issue with implementing autocomplete in the Monaco Editor using a file called tf.d.ts that contains all the definitions in TypeScript. Despite several attempts, the autocomplete feature is not working as expected. import React, { useRef, ...

The PHP query that was sent through an AJAX POST request is not being executed correctly

I have a situation where I am working with two pages: Page 1: <input type="hidden" name="rateableUserID" value="<?php echo $rateableUserID;?>"/> <input type="hidden" name="rateablePictureID" value="<?php echo $rateablePictureID;?>"/& ...

Exploring the World of Images with Javascript

I'm currently working on creating a slideshow using HTML and JavaScript. My goal is to have the image change each time I press a button that I've established (see code below). After reviewing my code multiple times, I still can't figure out ...

In JavaScript, implement event listeners exclusively on the main container and its immediate child elements

Is there a way to target just the main container and its second child elements for an event? Specifically, targeting id="container" and all elements with class="secondChild" Currently, I have a listener attached to all elements inside ...

Using b-icon with the <td> tag in VueJS

I am looking to incorporate HTML content within a table data element using VueJS. Below is an illustration of my situation: <template> <div> <div v-if="someObject.properties" style="margin-top: 20px;" class="table-responsi ...

"ExceptionThrownByMoveTargetOutOfBounds in Selenium WebDriver for IE9 and Firefox

Having trouble with the FireFox/IE9 driver in Selenium? When using the Actions class and its moveToElement method, I keep encountering a MoveTargetOutOfBoundsException error. Despite trying different solutions like Coordinates, Point, and javascriptexecuto ...

Error: Express JS custom module cannot be located in the root directory's modules folder

The file structure of my express js app resembles thishttps://i.sstatic.net/57NIQ.png I'm attempting to load a modules folder from the root directory. routes/users.js var express = require('express'); var router = express.Router(); var md ...

Mismatched data types for function arguments

const x: Example = { toY: (y: Maple) => { return y.p; } }; interface Example { toY: (y: Pine) => void; } interface Pine { c: string; } interface Maple extends Pine { p: boolean; } Despite the warning for interface names ...

What is the best way to coordinate text and photos within Bootstrap?

Currently, I am working on a bootstrap website that features a slideshow with 3 photos. The jQuery function responsible for this is as follows: $(function () { $.vegas('slideshow', { backgrounds: [{ src: 'img/ph1.jpg ...

Firebase issue: The function ref.once is throwing an Uncaught TypeError and is not recognized

I am attempting to utilize Firebase for both uploading a file and storing it in my database simultaneously. I want to track the number of uploads so that I can rename each file uniquely. While I have successfully uploaded and stored a copy in the database, ...

What is the method for creating a function using the const keyword in JavaScript?

I trust you are doing well. Recently, I have embarked on a coding journey and encountered an interesting challenge. The task requires me to create a function that outputs specific weather conditions for different countries to the console: The weather in ...

Utilizing jQuery or Javascript to obtain the title of the current webpage, find a specific string within it, and then apply a class to the corresponding element

Let's imagine I start with this: <title>Banana</title> and also have some navigation set up like this: <ul id="navigation"> <li> <a href=#">Banana</a> </li> </ul> Upon loading the sit ...

Exploring the method to retrieve data on the server side through Express when it is shared by the client within a put request

Here is the angular http put request I am working with: sendPutRequest(data) : Observable<any>{ return this.http.put("http://localhost:5050", data).pipe(map(this.handleData)); } After making this call, the server side method being invoked is ...

The function cannot be accessed during the unit test

I have just created a new project in VueJS and incorporated TypeScript into it. Below is my component along with some testing methods: <template> <div></div> </template> <script lang="ts"> import { Component, Vue } from ...

Failed to retrieve the requested item using fetch, encountering a NetworkError

My API is being accessed to retrieve data using this code snippet. It sends the email and password to the API: onSubmitSignIn = () => { fetch('http://localhost:3001/signin', { method: 'post', headers: {'Content-Type&ap ...

"Utilizing Jquery to extract data from a form field and combine it with a URL for maximum value

Today, I am delving into the world of jQuery for the first time and finding myself in need of some assistance with a particular problem. While this issue may seem trivial to experienced individuals, it is posing quite a challenge for me. The dilemma lies ...

Implementation of Gallows Game

SITUATION Recently, I took on the challenge of creating a "HANGMAN" game using JavaScript and HTML exclusively for client-side machines. The logical part of the implementation is complete, but I am facing a hurdle when it comes to enhancing the aesthetics ...