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

Experience the power of Vue Google Chart - Geochart where the chart refreshes seamlessly with data updates, although the legend seems to disappear

I have integrated vue google charts into my nuxt project. Whenever I select a different date, the data gets updated and the computed method in my geochart component correctly reads the new data. However, the legend or color bar at the bottom does not funct ...

Injecting a service into a parent class in Angular 6 without the need to pass it through the constructor

Can anyone provide guidance on how to incorporate a service with multiple dependencies into an abstract class that will be inherited by several classes, in a more streamlined manner than passing it through all constructors? I attempted to utilize static m ...

TS2322: Subclass missing property, yet it still exists

In my project, I have defined two Angular 4 component classes. The first class, referred to as the superclass: export class SectionComponent implements OnInit { slides: SlideComponent[]; constructor() { } ngOnInit() { } } And then there&apo ...

How can I prevent unnecessary rerenders when choosing an array in React Redux?

Is there a method to extract a derived array from a Redux store without triggering unnecessary renders? Within my Redux store, I have an array of objects. state = {items: [{id: 1, keys...}, {id: 2, keys...}, {id: 3, keys...}, ...]} I have created a selec ...

Implementing a mysterious key in the v-model when using a for loop in Vue.js

I have a dynamically generated object of facets. An example of the data might look like this: facets: { type: ['type1', 'type2', 'type3'], color: ['color1', 'color2'] } I also have an empty object ...

Encountering a VueJS error when trying to locate a module while using a JSON file

I've been tasked with finding a solution to dynamically import pages within vuejs projects that are being built with a CLI tool by my team. I initially attempted to use functions as a string ("() => import(...)") and then evaluate that string, but ...

The srcSet functionality in the Image component seems to be malfunctioning in the next.js framework, as it is failing to display

Check out my Next.js code snippet below: import React from "react"; import style from "@/styles/Home.module.css"; import Image from "next/image"; function index() { return ( <> <div className="contai ...

Troubleshooting Cross-Origin Read Blocking with the Google Maps Elevation API using Axios in a Vue.js Application

I'm currently working on integrating the Google Maps API into a Vue.js project. I've encountered an issue with two Google Maps services: - The Time Zone API is functioning properly. - However, the Elevation API is giving me a Cross-Origin Read Bl ...

Can someone explain the meaning of this syntax in a TypeScript interface?

Just the other day, I was trying to incorporate the observer pattern into my Angular 4 application and came across this TypeScript code snippet. Unfortunately, I'm not quite sure what it means. Here's the code: module Patterns.Interfaces { ...

Verifying the truthiness of a V-If label with Jest in a unit test is always a

Trying to check the validity of a label using Jest: <label class="no-content-label" v-if="products.length===0 && !isTableBusy">No Content To Show</label> and here is the test being used: it('Ensuring "No Conten ...

Exploring additional information

While trying to access data from an external API and display it, everything was running smoothly. I used the following code: <tr v-for="cv_output in cv_outputs" :key="cv_output.id"> <td>{{ 'test ...

Context API is failing to work in components that use children when the version is v16.6.0 or higher

Currently, I am utilizing the latest context API of React (v16.6.0 or higher) by specifying the public static contextType inside the component that consumes the context. Everything works smoothly unless the component declaring the Provider directly include ...

Enhancing Website Performance with Vue.js 2.0 Lazy Loading

I'm attempting to implement Lazy Loading for my components in Vue.js 2.0 (within a Laravel 5.3 project). As per the guidelines, I should proceed like this: Vue.use(VueRouter); const Forum = resolve => require(['./Components/Forum/Forum.vue& ...

Building a Dynamic Checkbox Validation Feature in Angular Using Data retrieved from an API

Currently, I have a function that retrieves and displays a list obtained from an API: displayEventTicketDetails() { this.Service .getEventTicketDetails().subscribe((data: any) => { this.eventTicketDetails = data.map(ticket => ticket. ...

What is the best way to interweave my objects within this tree using recursion?

I am working on creating a new function called customAdd() that will build a nested tree structure like the one shown below: let obj = [] let obj1 = { key: "detail1Tests", id: "94d3d1a2c3d8c4e1d77011a7162a23576e7d8a30d6beeabfadcee5df0876bb0e" } ...

Encountering an unexpected error with the InvalidCharacterError in IE11 when using VEE Validate in conjunction with Vue.js and babel-p

Encountering an issue in IE11 where I receive an InvalidCharacterError when attempting to validate a form using vee validate in vue.js. It seems like it might be related to a polyfill error, but I'm uncertain. I have tried debugging by removing certai ...

"Encountered a problem with Next JS API while trying to fetch data from the app directory

import { NextResponse } from "next/server"; export async function POST(request: Request) { const data = await request.json(); console.log(data); return NextResponse.json({ foo: "boo" }); } next version = "next": &quo ...

Utilize API within an array to enable Ionic to display a PDF in a document viewer

Recently diving into the world of Angular and Ionic, I've come across some interesting API data: [{"ID":"1","Title":"Maritime Safety","File_Name":"9c714531945ee24345f60e2105776e23.pdf","Created":"2018-11-07 17:36:55","Modified":"2018-11-07 17:36:55"} ...

TypeScript is throwing an error about a missing property, even though it has been defined

Within the PianoMK1Props component, there is a prop known as recording which accepts an object with specific properties. The structure of this object is defined like so(the state variable): const [recording, setRecording] = useState({ mode: "REC ...

Using Angular 5 to link date input to form field (reactive approach)

I'm encountering an issue with the input type date. I am trying to bind data from a component. Below is my field: <div class="col-md-6"> <label for="dateOfReport">Data zgłoszenia błędu:</label> <input type="date" formC ...