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

Can you identify the selected item on the menu?

My goal is to highlight the menu item for the current page by adding a "current" class. I've tried several code snippets from this website, but most of them didn't work as expected. The code I'm currently using almost works, but it has a sma ...

Using Vue to iterate through elements

I am struggling to loop through an array in a Vue component without duplicating the element specified in the 'v-for' directive. I have consulted the official Vue.js API documentation, as well as various online articles, but haven't found a s ...

JavaScript - An unexpected error occurred: Syntax error, unrecognized expression: [href=#contact] (WordPress)

I am currently working on a feature that involves adding a class to a specific menu item when a certain section is in view. However, I encountered an error that reads: Uncaught Error: Syntax error, unrecognised expression: [href=#contact] Your help would ...

Encountering a 400 Status Error in Shopware stating "The value provided is too lengthy. Please limit it to 255 characters or less" when attempting to update a database table

Whenever I attempt to insert data into the Shopware 6 database table, I consistently receive a 400 status response along with the message This value is too long. It should have 255 characters or less. The field in question that I am trying to update, desc ...

Selected a radio button within a jQuery UI dialog box

After using jquery-ui, I was able to create a simple dialog window. It looks like this: <div id="dialog-form" title="Add Attribute Category"> <input type="radio" id="priceable" name="price" value="true" checked="checked"/> Priceable &l ...

Slideshow of table rows in HTML

On a webpage, I am populating an HTML table with a random number of rows ranging from 1 to 100. Regardless of the total number of rows, the requirement is to display only 10 rows at a time on the screen and then shift to the next set of 10 rows every 5 sec ...

Creating an array outside of a function using Vue's component syntax

I need to create a global array within a vue.js component that can be accessed in all methods. Where should I declare this array within the component? I attempted to set it within the PROPS, but this resulted in an object when I actually require an array ...

Setting up a recurring task with a while loop in a cron job

Discover numerous libraries dedicated to implementing cron jobs in NodeJS and Javascript, allowing for hosting on a server. Ultimately, cron jobs are simply repetitive tasks set to run at specific times/dates. This led me to ponder the distinction betwee ...

Is there a way to efficiently retrieve multiple values from an array and update data in a specific column using matching IDs?

In my Event Scheduler spreadsheet, I am looking for a way to efficiently manage adding or removing employees from the query table in column A. Currently, I have a dropdown list in each row to select names and a script that can only replace one name at a ...

Tips for maintaining a sticky header while continuing to utilize Bootstrap table classes such as table-responsive and table-stripped

This is Here's my code on jsfiddle I've attempted to make the header sticky while maintaining the current layout, but every approach I've tried ends up messing with the responsiveness of the table. My next plan involves using a JavaScript ...

Guide to importing an npm package into a client-side file

Having some trouble importing the js-search npm package into my client-side .js file. The documentation suggests using import * as JsSearch from 'js-search';, but I keep getting a Uncaught TypeError: Failed to resolve module specifier "js-se ...

What is the best way to handle this unconventional JSON structure?

Looking for some insight on retrieving process information from a VPS with PM2. However, the JSON string returned by PM2 is malformed, making it impossible to run JSON.parse(). An example of the output provided by PM2: '{data: 0, informations: " ...

I prefer children to have their own unique style, instead of inheriting their parent's CSS

I currently have a project structured in the following way: There is an index page with a full layout Separate PHP files that are included in the index page Bootstrap is used in the index page, however, in some of the separate PHP files I also use jqgri ...

The background image is not displaying correctly in the tag td

I'm struggling to display a background image inside a table data cell using CSS. <td class='details-control'></td> When I use the following CSS rules, the image is not displayed: td.details-control { background: url(http:// ...

Ways to gather all the elements on each page

Currently engrossed in a web scraping endeavor for a car website utilizing Selenium. One potential roadblock I've encountered is that the code seems to only iterate over the initial car element on the page, instead of going through the entirety of ava ...

Ways to eliminate the blue selection box when dragging canvas objects in fabric framework

I've been trying to find a solution to remove the annoying blue highlight box that appears when dragging on the canvas while using fabric js, but so far I haven't had any luck. I've tried the following code, but it only works for text and n ...

Creating an XPath expression for selecting multiple siblings of a div tag

Currently, I am working on writing an XPath expression for a specific section of code: <div class="line info"> <div class="unit labelInfo TextMdB">First</div> <div class="unit lastUnit"> <div clas ...

The Value Entered in Angular is Unsaved

I have encountered an issue with my app's table functionality. The user can enter information into an input field and save it, but upon refreshing the page, the field appears empty as if no data was entered. Can someone please review my code snippet b ...

Determine whether I am verified or if the XMLHttpRequest has been directed

When making an XMLHttpRequest to an API secured with OAuth authentication, I encountered a situation where calling the API from a browser without being logged in automatically redirected me to the provider's login page. However, when attempting to ca ...