After submitting the form, Axios sends multiple requests simultaneously

Recently, I embarked on a small project that involves using Laravel and Nuxt Js. The main objective of the project is to create a form for adding users to the database. Everything seems to be progressing smoothly, but there's a minor issue that I've encountered - my axios script sends multiple requests in what appears to be a loop:

Here is the complete code snippet:

<script>

import $ from 'jquery'
import Swal from 'sweetalert2'
import toastr from 'toastr'
import Vue from 'vue'
Vue.component('pagination', require('laravel-vue-pagination'))

export default {
  layout: 'app',
  data () {
    return {
      laravelData: {},
      formFields: {},
      search: null,
      refresh: false
    }
  },
  watch: {
    refresh () {
      this.store()
      this.refresh = false
    }
  },
  mounted () {
    $('a.just-kidding').hide()
    this.index(1)
  },
  methods: {
    index (page = 1) {
      this.$axios.$get('/customer?page=' + page).then((response) => {
        this.laravelData = response
        this.refresh = true
      })
    },
    store () {
      const formData = $('#add-customer').serialize()
      return this.$axios.$post('/customer/store', formData).then((response) => {
        this.refresh = true
      })
    },
    find () {
      if (this.search === '') {
        this.index()
      } else {
        this.$axios.$get('/customer/find?customer=' + this.search).then((response) => {
          this.laravelData = response
        })
      }
    },
    destroy (customerId) {
      Swal.fire({
        title: 'Are you sure?',
        text: "You won't be able to revert this!",
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
      }).then((result) => {
        if (result.value) {
          // this.$Progress.start();
          this.$axios.$get('/customer/destroy?customer=' + customerId).then((response) => {
            if (response.success) {
              toastr.success(response.error, 'Ahoy Hoy !!', { 'positionClass': 'toast-top-left' })
              this.refresh = true
            } else {
              toastr.error(response.error, 'Owh :( !!', { 'positionClass': 'toast-top-left' })
            }
          })
          // this.$Progress.finish();
        }
      })
    }
  }
}
</script>

In addition, here is a snippet from my controller:

public function store(Request $request)
{

    DB::transaction(function () use ($request){
        $customerQuery = Customer::create($request->post('general'))->id;
        $shippingInfos = array_merge(array('customer_id' => $customerQuery), $request->post('address'));
        $shippingQuery = Shipping::create($shippingInfos);
        return true;
    });
}

Moreover, I have implemented a Middleware page called cors in my laravel application:

    <?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    public function handle($request, Closure $next)
    {
        return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    }
}

Answer №1

  observe: {
    update () {
      this.save()
      this.update = false
    }
  },

This could potentially create an endless cycle, as the modification of this.update within the observing function for monitoring this.update will continually call the observation function, leading to a recursive chain of events where it gets updated repeatedly.

The pattern is evident.

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

Implement a feature in JavaScript that highlights the current menu item

I'm currently developing a website at and have implemented a JavaScript feature to highlight the current menu item with an arrow. The issue I'm facing is that when users scroll through the page using the scrollbar instead of clicking on the men ...

Unable to retrieve the value of a textbox located within a gridview

In my grid view, I have a textbox nested inside a TemplateField. I want to retrieve the value of this textbox when a button is clicked: This is where I create the textbox: <ItemTemplate> <asp:TextBox runat="server" ID="txtEmail" Text=&a ...

Avoiding the occurrence of moiré patterns when using pixi.js

My goal is to create a zoomable canvas with rectangles arranged in a grid using pixi.js. Despite everything working smoothly, I'm facing heavy moire effects due to the grid. My understanding of pixi.js and webgl is limited, but I suspect that the anti ...

Struggles with ajax and JavaScript arise when attempting to tally up grades

Currently, I am facing an issue with my JavaScript. The problem arises when trying to calculate marks for each correctly chosen answer based on information from the database. If an incorrect answer is selected, the marks are set to '0', otherwise ...

Troubleshooting the issue of "Mismatched transaction number*" in MongoDB and Node.js

While trying to add data, I encountered an issue with modifying two schemas using ACID transactions in MongoDB with Node.js. Upon running the program, an error was displayed: (node:171072) UnhandledPromiseRejectionWarning: MongoError: Given transaction n ...

Error: doc.data().updatedAt?.toMillis function is not defined in this context (NextJs)

I encountered an error message while trying to access Firestore documents using the useCollection hook. TypeError: doc.data(...)?.updatedAt?.toMillis is not a function Here is my implementation of the useCollection Hook: export const useCollection = (c, q ...

When the clearOnBlur setting is set to false, Material UI Autocomplete will not

I recently encountered an issue in my project while using Material UI's Autocomplete feature. Despite setting the clearOnBlur property to false, the input field keeps getting cleared after losing focus. I need assistance in resolving this problem, an ...

Unusual JavaScript Bug: Uncaught TypeError - Unable to access property 'url' of null

I encountered a peculiar JavaScript error. The following message appears in the console: Uncaught TypeError: Cannot read property 'url' of null (Line 83) The code on Line 83 looks like this: var image = '<img class="news_image_options ...

Dropzone failing to verify the maximum file limit

I am currently using dropzone to upload files on my website. I have limited the number of files that can be uploaded to a maximum of six. The code works perfectly when uploading one image at a time, but if I select more than six images by holding down the ...

Tips for sending the setState function to a different function and utilizing it to identify values in a material-ui select and manage the "value is undefined" issue

I am currently utilizing a Material UI select component that is populated with data from an array containing values and options. Within this array, there exists a nested object property named "setFilter". The setFilter property holds the value of setState ...

Problem encountered when attempting to add elements to an array within a nested

When running this code, everything works correctly except for the array pushing. After checking the console.log(notificationdata), I noticed that notification data gets its values updated correctly. However, when I check console.log(notifications), I see ...

"The website seems to be experiencing some technical difficulties on Firefox, but I have switched to

I attempted to reset the text area after sending a message with the code below: $(document).keypress(function (e) { if (e.which == 13) { e.preventDefault(); var $form = $('#f1'); $.ajax({ url: $form.attr( ...

Angular event triggered when updating input values from the model

I have developed a custom directive to add functionality to input fields with a specific class. I want to trigger events on blur and focus to update the label style based on Material Design principles. However, when using ng-model in Angular, I also need t ...

Guide to writing a Jasmine test case to verify Toggle class behavior within a click event

My directive is responsible for toggling classes on an element, and it's working as expected. However, I seem to be encountering an issue with the jasmine test case for it. // Code for toggling class fileSearch.directive('toggleClass', func ...

prismjs plugin for highlighting code displays code in a horizontal format

If you're looking for a way to showcase source code on your website with highlighted syntax, prismjs.com may be just what you need. It offers a similar style to monokai... However, I've encountered an issue where the plugin displays my code in a ...

In the frontend, I seem to have trouble accessing elements of an array using bracket notation, yet strangely it works flawlessly in the backend

I am encountering a peculiar issue as a newcomer to coding. I have an array retrieved from the backend database, and my goal is to access individual elements of this array in the frontend using bracket notation. While I can successfully access the elements ...

What is the solution for handling nested promises in Node.js?

I am currently using the node-fetch module for making API calls. I have a function that handles all the API requests and returns both the status code and the response body. The issue I'm facing is that when returning an object with the response data, ...

Extract data from an ajax request in an AngularJS directive and send it to the controller

I am currently experimenting with integrating the jQuery fancy tree plugin with Angular. The source data for the tree is fetched through an ajax call within my controller. I am facing a challenge in passing this data to my directive in order to load the tr ...

The quickForm Meteor encountered an exception in the template helper: There was an error stating that Recipes is not within the window

I'm having trouble getting the app to work on Meteor. The quickform is not connecting to my Collection. "Error: Recipes is not in the window scope" Can anyone offer assistance with this issue? Below is my quickform code: <template name="NewRe ...

Display the menu and submenus by making a request with $.get()

My menu with submenu is generated in JSON format, but I am facing issues displaying it on an HTML page using the provided code. Can someone please assist me in identifying what mistakes I might be making? let HandleClass = function() { ...