Every change to the data in Nuxt.js triggers a form submission

This is my form:

<template>
    <div class="flex flex-col mt-[5rem] gap-4 p-4 items-center max-w-4xl mx-auto">      
        <form id="inquiry" class="flex flex-col gap-4 w-full" @submit.prevent="submitHandler">
            <label for="name">Full Name</label>
            <input class="input" type="text" name="name" v-model="formData.name" @input="saveFormData">
            <label for="email">Email Address</label>
            <input class="input" type="email" name="email" v-model="formData.email" @input="saveFormData">
            <label for="message">Your Message</label>
            <textarea class="input" name="message" id="message" cols="30" rows="10" v-model="formData.message"
                @input="saveFormData"></textarea>
            <h2 v-if="message">{{ message }}</h2>
            <button type="submit" class="btn" :disabled="message === 'Loading...'">Submit</button>
        </form>
    </div>
</template>

<script setup lang="ts">

const message = ref('');
const formData = reactive({
    name: '',
    email: '',
    message: ''
});

const loadFormData = () => {
    const savedData = localStorage.getItem('inquiryFormData');
    if (savedData) {
        const parsedData = JSON.parse(savedData);
        formData.name = parsedData.name || '';
        formData.email = parsedData.email || '';
        formData.message = parsedData.message || '';
    }
};

const saveFormData = () => {
    localStorage.setItem('inquiryFormData', JSON.stringify(formData));
};

const clearFormData = () => {
    localStorage.removeItem('inquiryFormData');
};

onMounted(() => {
    loadFormData();
});

const submitHandler = async () => {
    if (message.value === 'Loading...') return; 
    message.value = 'Loading...';

    const { data: res } = await useFetch("***", {
        method: "POST",
        query: {
            websiteId: "***",
            formGroupId: "***"
        },
        body: formData
    });

    const responseMessage = (res.value as any).message;
    message.value = responseMessage === "success"
        ? "Thank you! We will be in touch shortly."
        : "Oops, something went wrong. Please try again later.";

    formData.name = '';
    formData.email = '';
    formData.message = '';
    clearFormData();
};


</script>

After submitting the form, a second submission occurs with empty fields. If I don't clear the fields, every change triggers an additional submission. The handler appears to be monitoring field changes. While only called once based on log information, the data is sent multiple times.

Answer №1

useFetch is designed to automatically monitor changes in parameters. This means that when the form fields are cleared, another update is triggered.
To prevent this behavior, simply include watch: false in the options for the useFetch function.

For more information, refer to the official documentation

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

I am working with a JSON Object in JavaScript and need to retrieve a key using a String variable

Working with a JSON Object in JavaScript can be tricky, especially when trying to access keys stored as Strings using the dot operator. Consider this example of JSON code: "values" : [ { "prop0" : "h", "prop1" : "pizza", "prop2" : "2014- ...

Encountering an unexpected identifier error in Sails JS

As a newcomer to Sails JS, I am attempting to perform CRUD operations with it. However, I am encountering an unexpected error in my index function. I am struggling to identify where the mistake lies. // Usercontroller.js file module.exports = { creat ...

Tips for styling an array of objects using mapping techniques

I have an array of messages and I am currently using the map() function. Each message in the array has two keys - one for the author and another for the message content. What I want to achieve is to change the styles of the div tag when displaying the last ...

Collaborative Artistry: Using HTML5, JavaScript, and Node.js for Multiplayer

Creating a multiplayer drawing application for touch-enabled devices has been a challenge. I have utilized Node.js with Socket.io to draw points on a canvas, but there's an issue with the touchend event not resetting properly. To illustrate, take a l ...

Is there a way to execute a JavaScript function on a webpage using Selenium automation?

Here's an element on a website: <span class="log-out-ico" ng-click="logout()"> Instead of clicking it, I want to run the "logout()" script from selenium. Is that possible? If so, how can I do it? This is what I attempted: I ...

Whenever a user tries to retrieve a page using ajax and then proceeds to submit the form associated with that page, they encounter

In my addQuestions.php file, I have four options available - single, multiple, matrix, and true false type questions with values 1-4 assigned to each respectively. To dynamically load the appropriate question type based on user selection, I am using AJAX w ...

Discovering all the links present on a webpage using node.js

Currently, I am diving into node.js (webdriver) and encountering some challenges. Despite my efforts to search online for examples of the tasks I need help with, I have come up empty-handed. One example that has me stumped is how to log all links from a pa ...

ng-click not functioning correctly within templateUrl directive

Apologies if this appears to be a silly question, but I am new to Angular. I am facing an issue with an ng-click event that was functioning correctly until I moved the code into a directive. I suspect it has something to do with the scope, but I'm una ...

The parameters remain consistent across all Angular directives

I have created a directive called 'filterComponent' with the following code: app.directive('filterComponent', function() { return { restrict: 'E', templateUrl: 'filter-component.html', link: function ...

VueJS - Building a Form Template Within a Modal Component

Struggling to include a template in a modal and unsure how to pass variables to the child template: Below is the main HTML for the application: <div id="example" class="container"> <button class="btn btn-primary" type="button" @cli ...

What is the procedure to incorporate login credentials into the source of an iframe?

Is there a way to pass user auto login in the src URL? <iframe src="https://secure.aws.XXX.com/app/share/28228b0ccf0a987" width="1060px" height="1100px"></iframe> I attempted to achieve this, but it still shows the login screen <ifr ...

Displaying items using a filter function in ng-repeat

I am facing an issue with using a filter on my ng-repeat that involves a function with a parameter passed in, but for some reason, the filter is not working as expected. The function I am using for the filter compares two arrays to find any matching eleme ...

Changes in props do not automatically update children via Ref

I'm working on a React component that needs to update whenever the width changes: import { useRef, useEffect, useState } from "react"; function Child({ containerWidth }) { console.log("CHILD", containerWidth); return <div&g ...

React JS: How to prevent Yup and Formik error messages from being displayed multiple times upon submission

I have implemented Yup and Formik in my Sign up form to handle validation. My goal is to display specific errors based on the Yup validation rules I've set up. Take a look at the code snippet below: import React from 'react'; import { ...

Tips for styling Ajax.ActionLink elements with CSS

Hi there, I'm trying to style a navigation bar using CSS. I'm pulling the navigation bar values from a database using Ajax.ActionLink. I attempted to use JavaScript but encountered an error stating "jQuery is not defined", Here's the cod ...

Transferring a JavaScript variable to JSP using AJAX

I'm struggling to figure out the correct syntax to pass a JavaScript variable named "textVal" to a jsp file. Here is my code snippet: function show(textVal){ AJAX.onreadystatechange = handler; AJAX.open("POST","service.jsp",true); AJAX.setR ...

Are there problems with the response values of functions that can handle varying object interfaces?

Currently in the process of developing a command line blackjack app with Node and Typescript, even though I am relatively new to Typescript. My main challenge lies in implementing interfaces for player and dealer objects, as well as creating functions that ...

Is it possible for the Redux inside a React component from npm to clash with the Redux in the container?

I am looking to bundle a React component with npm and incorporate Redux to handle state within the component. If another React project imports my component, will it cause conflicts with the Redux instance of that project? For example: The component code ...

Obtaining targeted information from JSON using JavaScript

Extracting specific data from a JSON object can be challenging, especially if you are new to JavaScript. Below is an example of JSON data containing various fields: {"Date":"2021-01-31........ to ....10.9,"windDir":"SSE"} ...

HTML element DIV positioned above the iframe

I am looking for a way to automatically place a "PLAY" div above each iframe instead of doing it manually. I have successfully done it manually but I'm not sure how to achieve the same result with a script or using CSS. Below is my HTML markup: < ...