Exploring the application of the PUT method specific to a card ID in vue.js

A dashboard on my interface showcases various cards containing data retrieved from the backend API and stored in an array called notes[]. When I click on a specific card, a pop-up named updatecard should appear based on its id. However, I am facing issues connecting the updateNote.vue component to the backend API (PUT-method). The updateNote functionality relies on the id of the clicked card, but I am unsure how to pass this particular id into the updateNote URL. Any assistance in resolving this problem would be greatly appreciated. [Screenshot of incorrect hitting API URL]

DisplayNotes.vue

<template>
<div class="carddisplay-section">
    <div v-for="note in notes" :key="note.id" id="blur" class="container note">
        <div @click="toggle(note.id)" class="card-content">
            <h5>{{note.title}}</h5>
            <p>{{note.body}}</p>
        </div>
        <div class="import-icons">
            <icons class="imported-icons note-icons" />
            <button v-if="flag" class="card-button" type="button" @click="handlesubmit();Togglebtn();">Close</button>
        </div>
    </div>
    <div id="popup">
        <UpdateNotes :cardId="clickedCard"/>
    </div>
</div>
</template>

<script>
import service from '../service/User'
import icons from './icons'
import UpdateNotes from './UpdateNotes.vue'
export default {
    name: 'DisplayNotes',
    components: {
        icons, UpdateNotes
    },
    data() {
        return {
            flag: true,
            notes: [{
                id: 1,
                title: 'Fundoo',
                body: 'unlimited notes..'
            }, ],
           clickedCard:'',
        }
    },
    methods: {
        Togglebtn() {
            this.flag = !this.flag;
        },
        async handlesubmit() {
            service.userDisplayNotes().then(response => {
                this.notes.push(...response.data);
            })
        },
        toggle(id){
            var blur=document.getElementById('blur');
            blur.classList.toggle('active');
             this.clickedCard = id;

            var popup=document.getElementById('popup');
            popup.classList.toggle('active');

        },
        // myIndex(){
        //     document.getElementById('blur').innerHTML=this.notes.findIndex();
        // }

    }
}
</script>

<style lang="scss">
@import "@/styles/DisplayNotes.scss";
</style>

UpdateNotes.vue

<template>
 <div class="update">
        <form class="update-note" @submit.prevent="handlesubmit" autocomplete="off">
            <input name="title"  v-model="title" placeholder="Title" />
            <textarea name="content" v-model="body" style="resize: none" placeholder="Take a note..." rows="3"></textarea>
            <div class="btm-icons">
                <icons />
                <button id="btn-section"  type="submit" @click="handlesubmit">Close</button>
            </div>
        </form>
    </div>
</template>
<script>
import icons from './icons.vue'
import service from '../service/User'
export default{
    components:{icons},
    props: ['cardId'],
     data() {
        return {
            title: '',
            body: ''
        }
    },
    methods:{
     async handlesubmit(){
       let userData={
id:this.cardId,
title:this.title,
body:this.body
       }
        service.userUpdateNotes(userData).then(response => {
         localStorage.getItem('token', response.data.token);  
               alert("Note updated successfully");
               return response;
            })
     }
    }
}

</script>
<style scoped>
.update {
  padding-top: 0%;
  
}

.update-note {
  position: relative;
  width: 550px;
  max-width: 100%;
  margin: 152px auto;
  margin-right: 80%;
  background: rgb(255, 255, 255);
  padding: 15px;
  border-radius: 5px;
  box-shadow: 0 1px 5px #ccc;
}
.update-note input {
  width: 100%;
  max-width: 100%;
  border: none;
  padding: 4px;
  outline: none;
  font-size: 1.2em;
}
textarea {
  width: 100%;
  max-width: 100%;
  border: none;
  padding: 4px;
  outline: none;
  font-size: 1.2em;
}
button {
  border: none;
  background: transparent;
  font-weight: 500;
  float: right;
  margin-top: -5%;
  cursor: pointer;
}

</style>

[contains API call methods] axios.js

// npm install axios --save
//axios.defaults.baseURL="http://localhost:8000/api"

import axios from 'axios'

axios.defaults.baseURL=process.env.VUE_APP_AXIOS_URL
axios.defaults.headers.common['Authorization'] = 'Bearer' + localStorage.getItem('token');

export default class AxiosService{
   postData(url, data){
       return axios.post(url, data).then(response =>{
           return response;
       }).catch(error=>{
           return error;
       })
   }
   getData(url){
        return axios.get(url).then(response=>{  
            localStorage.getItem('token', response.data.token);  
            return response;
       }).catch(error=>{
            return error;
       })
   }
   updateData(url, data){
       return axios.put(url, data).then(response=>{
           return response;
       })
   }
}

[includes backend API URLs and uses methods from axios.js] user.js

// import axios from 'axios';
import AxiosService from '../service/axios';
const axios = new AxiosService()

export default{
    userRegister(data){
        return axios.postData("/register", data);
    },
    userLogin(data){
        return axios.postData("/login", data);
    },
    userForgot(data){
        return axios.postData("/auth/sendPasswordResetLink", data);
    },
    userReset(data){
        return axios.postData("/auth/resetPassword", data);
    },
    userCreateNote(data){
        return axios.postData("/createNote", data);
    },
    userDisplayNotes(){
        return axios.getData("/displayNotes");
    },
    userUpdateNotes(data){
        //actual URL is http://localhost:8000/api/updateNote/1 (where id= id of my card)
        return axios.updateData(`/updateNote/${id}`, data);
    }
}

Answer №1

To enhance the functionality of the userUpdateNotes function, modify it to

return axios.updateData(`/updateNote/${data.id}`, data);
. This change is necessary because you are passing data in the method instead of just the id. Therefore, if you wish to access the id, it must be done using data.id.

Additionally, opt for backticks (`) over double-quotes (") for improved syntax and clarity.

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

What is the best way to convert HTML into a React component?

This is the situation I am facing : 1) The application requests a CMS (Content Management System) for page contents. 2) The CMS responds with "<div>Hi,<SpecialButton color="red">My Button</SpecialButton></div>" 3) The applicat ...

Having trouble deleting a Repeatable Job from the Bull queue in Node.js

Upon attempting to utilize the removeRepeatableByKey method, I encountered an error stating that removeRepeatableByKey is not a function. Specifically, it mentioned that queue_1.taskQueue.removeRepeatableByKey is not a function. Furthermore, I am facing d ...

Navigating with NextJS to a personalized URL and managing the feedback from an external application

I'm currently in the process of developing an application that involves redirecting users to a specific URL, prompting them to open an app (with a url starting with zel:), and then sending a request back to my server. Here's the envisioned user j ...

Tips on assigning a reference to an element that has not been rendered yet

I've created a login page with a button labeled "Watch the video". When the button is clicked, it hides and reveals a video player. My goal now is to automatically start playing the video once it's displayed without requiring an extra play button ...

How can I wait for an onclick action to pause, loop, or continue inside of a loop?

The form's onsubmit function triggers a pop-up message asking the user if they want to proceed before submitting the form. This requires the onsubmit function to wait for the user's final input in order to fully execute the form. Here is the cod ...

"Initial loading issue with bootstrap carousel causes slides not to slide smoothly

I am currently working on implementing a slider carousel using Bootstrap. Although the 'active' image loads successfully, the controls and slide functionality are not working as expected. Initially, I believed this exercise would be straightforwa ...

What is the best way to ensure that a link fragment scrolls to the top of the page in Angular?

Having trouble with link fragments in my Angular single-page-app: <a href="/#/search">Search</a> When clicking this link, it takes me to the right page but keeps my scroll position. I want it to scroll to the top of the page so I'm curre ...

Using Vue.js within Cordova platform allows developers to create dynamic

Having trouble integrating a Vue.js app into Cordova. Everything seems to be working fine, except I'm unsure how to capture Cordova events (deviceready, pause, etc.) within my Vue application. Using the Webpack template from vue-cli. This is my file ...

Updating the file path for JS and CSS files in the finalized build

Looking for some guidance here. I'm trying to deploy a vuejs app using Vue CLI 3 and when I run the build command, the files are built into the dist folder as expected. However, there are js and css folders inside dist that contain the respective file ...

Prevent webpage from resizing when window dimensions change

Whenever I resize my webpage window, the elements start to pile on top of each other and it looks disorganized. For example, when I reduce the window size, YouTube just cuts off everything instead of stacking the images. How can I achieve a similar effec ...

Display fixed or absolute elements within a scrollable container

I want to create a unique design with overlapping divs that can be selectively displayed through scrolling. While this effect is possible with images using background-attachment: fixed, I am seeking a solution that can work for any child element. Here is ...

Is it possible to share a Vue.js component by "transferring" it rather than duplicating it?

In my comment system project using Vue.js, I have over 300 comments to manage. Each comment has an admin section that appears when the cursor hovers over it. Duplicating the admin section component for each comment is not ideal as it creates unnecessary l ...

How can I rename a parameter while uploading a file with Vue2-Dropzone?

While using Vue2-Dropzone to upload files, the default parameter name is set to "file". However, I would like to customize it and change it to "upload". I attempted to modify this by utilizing the vdropzone-sending method. Unfortunately, this resulted in ...

How can I position an element to the bottom right using CSS?

Is there a way to position this element to the bottom right corner? HTML <div class="info player"> <div id="job" style="display:none;"><span>Jobname</span></div> <div i ...

What is the best way to utilize SCSS variables alongside data-attributes within Vue JS and Bootstrap Vue?

I'm currently working on implementing a Dark Theme button for my application that can change the entire theme with just one click. Although the functionality is already in place, I am exploring ways to make this process simpler and more efficient. So ...

NodeJS assert.AssertionError: How can I eliminate this error?

For my school project, I decided to create a web service using IBM Bluemix. However, I encountered an "assert.AssertionError" when attempting to run the code with "npm start" in the Windows 10 Command Prompt on my localhost. Can someone help me understan ...

Exploring the differences between React state and CSS :hover in the context of a dropdown menu that is accessible to both desktop users (via mouse) and

I have come across a dilemma regarding a dropdown menu that needs to cater to both Desktop/PC users (with mouse) and Mobile devices (with touch). After considering my options, here are the proposed solutions: OPTION 1 One approach is to implement it usi ...

Tips for extracting the content from a <span> tag within an iframe

In my setup, I have two iframes labeled Test1 and Test2. Each iframe contains the following code snippet with the goal of retrieving the value '24' from it. <div class="Test-font"> <h6 class="Test_something d-inline">Available MQ ...

What is the best way to eliminate the space between two columns of a row in Bootstrap 5 grid system?

In my quest to achieve the grid layout illustrated in the image below https://i.sstatic.net/4hsjw.jpg .col_1{ background-color: bisque !important; height: 500px; } .col_2 { width: 300px; height: 287px; background-position: cent ...

``Is there a way to effectively assess the Angular UI-Grid cellTemplate function in the attribute value only when it is displayed

Utilizing angularjs and ui-grid with a custom cellTemplate, each cell contains an object referred to as COL_FIELD. This object is passed to a function that generates an image data URI used in the src attribute of the cellTemplate to display images within e ...