I'm looking to learn how to implement the delete method in an API using TypeScript. Can anyone help me out

I am seeking guidance on utilizing 'axios' within 'nuxt.js'. I have experimented with sample data, and I am particularly interested in learning how to utilize the 'axios' method within 'nuxt.js' using TypeScript.

The post method was successful, which led me to believe that the delete method would follow a similar code pattern as the post method. However, when attempting the delete method, it did not function as expected. I am unsure of how to resolve this issue. Does anyone have any insights? The relevant code is displayed below.

<template>
  <div>
    <v-row>
      <v-col cols="3">
        <v-text-field v-model="name"></v-text-field>
      </v-col>
      <v-col cols="3">
        <v-btn @click="createNewUser">CreateNewUser</v-btn>
      </v-col>
    </v-row>
    <v-row>
      <v-col>
        <ul>
          <li v-for="user in users" :key="user.id">
            {{user.name}}
            <v-btn @click="deleteUser(user.id)">DeleteUser</v-btn>
          </li>
        </ul>
      </v-col>
    </v-row>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from "nuxt-property-decorator";
import axios from "axios";

@Component({})
export default class extends Vue {
  users: object[] = [];
  name: string = "";
  
  async mounted() {
    axios.get("https://jsonplaceholder.typicode.com/users",{params:{name:'Glenna Reichert'}})
        .then(response=>this.users = response.data)
        .catch(response=>console.log(response));
    axios
  }

  createNewUser() {
    axios
      .post("https://jsonplaceholder.typicode.com/users", { name: this.name })
      .then((response) => this.users.unshift(response.data))
      .catch((response) => console.log(response));
  }
    
  deleteUser(id: any) {
    axios
      .delete("https://jsonplaceholder.typicode.com/users"+id)
      .then((response) => console.log(response))
      .catch((response) => console.log(response));
  }
}
</script>

Answer №1

Make sure to include the correct slash in your URL. Consider using template literals to minimize errors in your code.

async removeUser(userID:any){
   await axios.delete(`https://jsonplaceholder.typicode.com/users/${userID}`)
         .then((response) => console.log(response.status))
         .catch((response) => console.log(response.status));
}

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

Ways to showcase product information (Using Angular and Firebase)

Information product.model.ts id?: string; name: string; price: number; sale_price: number; description: string; tech_sheet: string; imageUrls: string[]; category: string; createdAt: Date; } Initialize file product.service.ts The latest f ...

What could be causing the lack of triggering Vue.js beforeUpdate, updated, and activated events during execution?

Can you identify which lifecycle hooks are executed in this vue.js code? beforeCreate created mounted but not: beforeUpdate updated activated Check out the code on jsFiddle var vm = new Vue({ el: '#app', data: function() { return ...

Issue with TypeScript version 4.2.1 - The Array.some() method does not support a function that returns a boolean

I encountered a TypeScript error that goes as follows: The complete error message reads: Supplied parameters do not match any signature of call target: parameter type mismatch. > Parameter 'Predicate' should have type assignable to {(value: ...

Is there a way to ensure that introjs follows the structure of slides effectively?

I created a modal that features multiple slides, each containing its own form. <v-bottom-sheet v-model="showCreateRecordModal" inset max-width="600px" class="rounded-t-xl" scrollable persistent> <v-card v-if=&quo ...

Comparison between Vue3 Composition Functions and importing functions from a module

Just finished going through the latest Composition API RFC (link). It covers various methods to reuse code across components, excluding the import from module method. Presumably because it focuses solely on VueJS and for comparison purposes. They provided ...

Struggling with setting up Angular Material and SCSS configuration in my application -

Hey there, I encountered an error or warning while trying to launch my angular app. Here's the issue: ERROR in ./src/styles/styles.scss (./node_modules/@angular-devkit/build- angular/src/angular-cli-files/plugins/raw-css- loader.js!./n ...

Generate a bootstrap component on a template using dynamic rendering

I am looking for a way to dynamically display a bootstrap icon in my template depending on the outcome of a function. Initially, I attempted the following approach: <template> <div> {{ getUsersEmai ...

Looking to retrieve CloudWatch logs from multiple AWS accounts using Lambda and the AWS SDK

Seeking guidance on querying CloudWatch logs across accounts using lambda and AWS SDK Developing a lambda function in typescript Deploying lambda with CloudFormation, granting necessary roles for reading from two different AWS accounts Initial exe ...

Specify the dependencies in the package.json file to ensure that the React package designed for React v17 is compatible with React v18 as well

Recently, I developed an npm package using React v17.0.2. The structure of the package.json file is as follows: { "name": "shoe-store", "version": "0.1.0", "private": true, "dependencies": ...

Achieve validation of numerous variables without the need for a string of if-else

If we have three variables, such as firstName, lastName, and email, how can we check if they are empty or not without using multiple if else blocks? let firstName = "John"; let lastName = "Doe"; let email = "john.doe@example.com"; if (firstName.trim() == ...

How to utilize Vue.js method to retrieve child prop?

In my Vue.js project, I have created two components. The main component uses a child component called NoteRenderer, which includes a prop named data_exchange. My goal is to update this prop from the main component when a button is clicked. I attempted to a ...

Setting up Laravel Echo and Pusher-JS in a VueJS application

I'm currently utilizing laravel-echo and pusher-js in a project that combines Laravel and VueJS, and it's functioning well. However, I now face the challenge of broadcasting in a pure VueJS project without any dependency on Laravel. I am uncert ...

Revise Swagger UI within toggle button switch

My project aims to showcase three distinct OpenApi definitions within a web application, enabling users to explore different API documentation. The concept involves implementing a toggle button group with three buttons at the top and the Swagger UI display ...

Unlocking app data properties in Vue 3: A comprehensive guide

I am currently in the process of transitioning to Vue 3. In my previous Vue 2 app, I could access properties like this: import { createApp } from 'vue/dist/vue.esm-bundler'; ... const app = createApp({ // el: 'app', // removed data ...

Utilizing a single v-model for several elements

I am having an issue with a dropdown that is set to v-model="compose.Recipient". Based on the value of "compose.Recipient", I need another dropdown to appear as shown below: <div class="form-group" v-if="compose.Recipient==2" title="Select Class"> ...

Leveraging interfaces with the logical OR operator

Imagine a scenario where we have a slider component with an Input that can accept either Products or Teasers. public productsWithTeasers: (Product | Teaser)[]; When attempting to iterate through this array, an error is thrown in VS Code. <div *ngFor= ...

When working with Typescript and React, you may encounter an issue where an element implicitly has an 'any' type because the type 'State' has no index signature. This can lead to

In my current mini project, I am using Typescript and React. As someone new to Typescript, I am currently in the process of learning it. Within the project, I have a state defined as follows: type State = { field1: string, field2: string, field3: n ...

Setting the title and meta tags in Nuxt.js using a middleware or plugin - a step-by-step guide

Is there a way to dynamically set NuxtJS title and meta tags using nuxt-middleware/nuxt-plugin? Currently, I am setting it in nuxt.config.js like this: head: () => { const now = Date.now() return { title: `config test : ${now}`, ...

Guide for Vue.js Bootstrap Table: Retrieving and Storing Row IDs in a Data Property

I'm working with a Vue.js Bootstrap table and I need to store each table row id in either an Array or Object data property. Below is a sample bootstrap table template: <template v-slot:cell(label)="row" > <div > ...

How to show the raw image content-type using Vue.js

When retrieving an image from a REST API through an HTTP GET with a request body, I have successfully verified the returned content using node.js and chai.js: expect(res).to.have.header('Content-Type', 'image/jpeg'); expect ...