The update function in my Vuejs3 project is not functioning as expected when trying to use JSON data to populate the

Recently, I started working with vuejs 3 and json. My goal is to update a course, however, despite my efforts, the fields for the course (title and content) remain empty with no errors being displayed. In views/blog/OnePost, I am passing the ID of the course as a props.

/views/blog/Edit.vue

<template lang="">
    <div class="row my-4">
        <div class="col-md-6 mx-auto">
            <h1 class="my-2">New Post</h1>
            <form @submit.prevent="editPost">
                <div class="form-group">
                    <label for="Title">Title</label>
                    <input v-model="post.title" id="title" type="text" class="form-control">
                </div>
                <div class="form-group">
                    <label for="Content">Content</label>
                    <textarea v-model="post.content" id="content" rows="3" class="form-control"></textarea>
                </div>
                <button class="btn btn-block btn-warning">update</button>
            </form>
        </div>
    </div>
</template>
<script>
export default {
    props: ['id'],
     data() {
        return{
         url: `http://localhost:5000/posts/${this.id}`,
            post : {
                title:   '',
                content: ''
            }
        }
     },
     methods: {
         editPost() {
             if(this.post.title == '' || this.post.content == ''){
                 return;
             }
             
            fetch(this.url, {
                method: 'PUT',
                headers: {'Content-Type' : 'application/json'},
                body: JSON.stringify(this.post)
            })
            .then(res => res.json())
            .then(data => this.$router.push('/blog'))
            .catch(err => console.log(err.message))
         }

     },
      mounted() {
       
            fetch(this.url)
            .then(res => res.json())
            .then(data => {
                this.post = data
            })
            .catch(err => console.log(err))
        
    }
    
}
</script>

/views/blog/OnePost.vue

<router-link :to="{ name: 'post-edit', params: { id: post.id }}" class="btn btn-sm btn-warning ml-3">edit</router-link>

Answer №1

Upon reviewing your code sample, there are a couple of issues that need to be addressed.

Firstly, it appears that there is a typo in your code where you have used hearders instead of headers.

Additionally, it is recommended to ensure that the button element within your form has the correct type attribute set to "submit". This is important as it enables the form's associated @submit handler to trigger properly.

If you would like more information on this topic, you can refer to the following link: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form

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

Is there a way to keep a JS script running even after navigating away in the Google Chrome console?

Assume there is a basic script available var x = 0; run(); function run() { console.log(x++); setTimeout(run, 1000); } If I input it into the Google Chrome console. How can I keep it running even after navigating to another page (continuously d ...

"Exploring the Power of Vue 3 Event Bus Through the Composition API

I recently set up mitt and I'm facing difficulties dispatching events to another component. The issue arises due to the absence of this in the setup() method, making it challenging to access the app instance. Here's my current approach: import A ...

Adjusting the Stripe Button to Utilize a Unique Button Class

I have a stripe button on my website and I want to add my custom class to it. I discovered that manually creating the CSS for it can work, but I prefer to maintain consistency across all buttons on my site by using my custom class. No matter what I attemp ...

Load information into array for jqGrid display

I am attempting to populate my JQgrid with data every time I click the "1" button, but I am encountering difficulties. As a newbie in jQuery, I am able to display the data in a p tag without any issues. Currently, I am considering whether to use push or a ...

Refresh the JavaScript graph with new data from the AJAX request

Seeking assistance in updating my javascript chart data using ajax data retrieved from a database. The specific chart being referenced is an apex chart. After submitting a form via ajax, the returned result is as follows: type: "POST",crossDomain ...

Angular 6: Utilizing async/await to access and manipulate specific variables within the application

Within my Angular 6 application, I am facing an issue with a variable named "permittedPefs" that is assigned a value after an asynchronous HTTP call. @Injectable() export class FeaturesLoadPermissionsService { permittedPefs = []; constructor() { ...

Is your Javascript color changer only changing the color on the second click?

My current challenge involves making my navbar highlight the active tab. The JavaScript I've written isn't functioning as expected - it only works on the second click, and even then, only if you double click. function changeNavColor(id){ var ...

Display directional arrow on Ext.grid when the page is initially loaded

Displaying a grid with the product ID is our current setup. While the data is sorted according to the product ID, the sort arrow does not display upon page load. I have observed that clicking on the column reveals the arrow. How can we ensure that the so ...

Creating an array with conditional elements in React involves utilizing the map method along with a conditional

My array, named tableFilterFields, looks something like this: const tableFilterFields = [ { label: "Start Date", name: "StartDate", type: FilterControls.DatePicker, defaultValue: new Date(new Date().setDate( ...

Setting a timeout from the frontend in the AWS apigClient can be accomplished by adjusting the

I am currently integrating the Amazon API Client Gateway into my project and I have successfully set up all the necessary requests and responses. Now, I am trying to implement a timeout feature by adding the following code snippet: apigClient.me ...

Get selectize.js to display only options that begin with the user's input

Using selectize.js, my current setup looks like this: https://i.sstatic.net/EqhF8.png Instead of only showing words that start with 'arm', it displays words or options containing 'arm' as a substring elsewhere. I want to modify the f ...

Bypass the pre-commit hook when using the "npm version" command

When using the npm version command, it will commit the change to package.json and create a tag. Is there a method to avoid the execution of commit hooks? ...

In the Android Chrome browser, the settings of the meta viewport attribute do not take effect when the device is in full screen mode

While using the fullscreen api in Android, I noticed that the values of meta viewport attributes like initial-scale and user-scalable are not reflected in the browser when in full screen mode. However, when not in full screen mode, these values work as exp ...

AngularJS does not allow empty spaces in textarea inputs

I am working on a form that includes a textarea element for users to input descriptions, however it does not allow any empty spaces. Users can only input alphanumeric and numeric characters, but no spaces. <textarea class="form-control" rows="4" maxl ...

What is the best method for transforming a JavaScript array of Objects to a different format?

Is there a way to transform this array of objects from one format to another? The original array is as follows: const data = [ {name: 'Customer 1', value: {Oil: 55, Gas: 66, Retail: 56}}, {name: 'Customer 2', value: {Oil: ...

Refresh the webpage when using the browser's back or forward button in AngularJS with ui-router

In my AngularJS app, I have configured the ui-router state as follows: $locationProvider.html5Mode(true); $stateProvider .state('index', { url: '/index?zoom&center', views: { ...

Prevent form submission when email is missing

function validateEmail(){ var TCode = document.getElementById('email').value; if(TCode.length==0) { email_info.innerHTML="This field is required"; return false; } email_info.innerHTML=" "; ...

Bringing PlayCanvas WebGL framework into a React environment

I am currently working on integrating the PlayCanvas webGL engine into React. PlayCanvas Github Since PlayCanvas operates on JS and the code remains in my index.html file, I am facing challenges in comprehending how it will interact with my React compone ...

Discover and update values in JSON using JavaScript

Currently, I am working on generating graphs using d3.js with a JSON file as the input. My main challenge lies in parsing the date and time format for the x-axis. Below is the code snippet that I have attempted: d3.json('data/fake_users11.json', ...

React - Survey.js... Users are reporting issues with the functionality of the EDIT button for survey items

Having trouble integrating Survey.js into my React application. I am able to load the Survey Editor interface initially, but I am encountering issues when trying to edit the questions. The "EDIT" and "..." buttons are unresponsive, triggering an error as d ...