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

How to implement a timeout feature in JavaScript/TypeScript for cloud functions

I'm currently facing an issue with trying to delay certain actions using Cloud Firestore. Despite my attempts, the setTimeout/setInterval functions don't seem to be working as expected in my code. export const onTimerCreate = functions.firestore ...

Specialized hover mission

Do you have a question? Imagine you have 3 spans where the default color is black. When you hover over a span, its color changes to red. But what if I told you that at the start, the first span has an orange color. Now, I want to hover over the orange on ...

Generating a dropdown menu in HTML using JSON entities

I am attempting to populate an HTML Select element with data retrieved from JSON. Below is a simplified version of the JSON object: {"Group1": "TestGroup1", "Group2" : "TestGroup2", "TotGroups" : "2"} To achieve this, I am using JQuery and AJAX for fetch ...

The response to ajax requests does not appear in Chrome Dev Tools

I'm experiencing an issue with my nodejs application where I encounter a peculiar situation when making ajax requests using jQuery. When I make a redirection in the callback function of the AJAX request, the response in the developer tools appears emp ...

Surprising Behavior of React's OnClick Event

Custom Component function ProductCard ({image, name, stats, id}){ let dispatch = useDispatch() let quantity = 1 return ( <> <div className="product-card" ...

Ways to avoid the browser from storing a JSON file in its cache

Hey there, I'm working on a project and running into some issues with caching. The problem I'm facing is that the browser keeps holding onto the json file containing save data even after I update it elsewhere. This means that the browser is readi ...

What steps should I take to set up search paths for node modules in Code Runner within Visual Studio Code?

Just recently, I embarked on a Javascript course and successfully configured my Visual Studio Code to run JavaScript. Check out the code snippet that I came up with: const prompt = require('prompt-sync')(); var fname = prompt("First name please : ...

What is preventing ng-click from assigning a variable with the value from ng-repeat in AngularJS?

I'm currently working on a feature for an app that allows users to select font styles from Google Fonts for specific text elements. Here's the code snippet I have so far: <ul ng-init='headerFont="mono"'> <li ng-repeat=&apos ...

Utilizing Angularfire OAuth for Facebook authentication in login strategy

After successfully implementing the code below in the loginCtrl controller and login.html, I encountered some issues with setting up the workflow correctly. My goal is to achieve something like this: //check if the current $scope has authData //if so red ...

Achieving uniform width in material ui: Tips for maintaining consistency

I am encountering an issue with the width of my Goal components and can't figure out what is causing it. https://i.stack.imgur.com/jPlyf.png Despite setting the width of the Paper selector to 100%, each Goal component's width remains inconsiste ...

What is the significance of property placement in a Mongo query: at the beginning versus at the

Currently, I am in the process of creating a query to retrieve data from the mango collection. Interestingly, I have written the same query in two different ways. Here is my working query: db.getCollection('routes').find({"routes.routeId": "r1q ...

Displaying various Vue components within Laravel 6.x

After diving into Laravel and Vue, I managed to put together a navigation component as well as an article component. The problem I'm facing is that although my navigation vue component is visible, the article component seems to be missing. Reviewing ...

Creating dynamic routes in react-router-dom using conditions

I'm currently developing an application using react-router-dom for navigation. I've encapsulated all my <Routes> inside a container provided by Material UI. However, I want my home page to be outside of this container so that I can display ...

Ways to extract link value in Angular

Is there a way to extract a value from a link using Angular 4? I have used *ngIf and would like to display a div based on the value within the link. <div *ngIf="obtain the value from the current href"> ...

Executing a function within JSX to dismiss a modal in NextJS

I am currently utilizing the Tanstack React Query library to perform a POST request from a Modal that includes a form: const addDay = (day: TDay) => { const apiURL = process.env.NEXT_PUBLIC_SERVER_URL const queryURL = apiURL + router ...

The initial request is replaced by new information

Trying to fetch data for autocomplete in Laravel. Controller: public function collection_search(Request $request) { $term = $request->search; $serveurapObj = new Serveurap(); $result = $serveurapObj->collectionAutocomplete(); ...

Sorry, I can't help with generating code that could potentially be harmful or used for malicious purposes

After downgrading my application from 5.5 to 5.4, I encountered an error when running php artisan serve: Call to undefined method App\Console\Kernel::load() - Laravel 5.4 I attempted to resolve the issue by executing composer dump-autoload ...

Animating a 3D object along a path in Three.js

I am trying to shoot a projectile from one mesh to another. I connected them with a line, but now I'm struggling to move the projectile along this path. The translateOnAxis function didn't seem to do the job. Do you have any suggestions for how ...

Having trouble retrieving POST data with the Webextensions API

Looking to retrieve POST data using a Webextensions API on page load. Implemented a background script with the code below: browser.webRequest.onBeforeSendHeaders.addListener( getPostData, { urls: ['<all_urls>'], types: ["main_fr ...

"Can you provide guidelines on how to retrieve data based on a specific

I am working on displaying dishes that are associated with specific restaurants. Each dish has a unique restaurant_id. Every restaurant is given an ID. Restaurant Migration Schema::create('restaurants', function (Blueprint $table) { $ ...