My API is called twice

Asked
Active3 hr before
Viewed126 times

4 Answers

twicecalled
90%

I also faced a similar problem but it turns out it was because my routes were going through the service worker which again requested and returned the request so the server got 2 requests 1 from the main fetch an another from the service workers fetch. EDIT facepalm yea I am new to pwas and all so was using return instead of respondWith(),Unlike “simple requests” (discussed above), "preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data., 2 Only runs once every five seconds if I try it. Almost definitely the problem is in something you're not showing us. Maybe the setInterval line is being called twice? – JLRishe Apr 25 '18 at 19:02 , Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers

The additional fetch request you are seeing is an OPTIONS request (pre-flight request) which is occurs when headers are passed in the request.

OPTIONS
load more v
88%

Read the question carefully.,Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.,View Unanswered Questions,If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.

[HttpPost]
        [Route("SaveClientDetails")]
        public async Task<httpresponsemessage> AddNewClient([FromBody]usp_GetClientDetails client)
        {
            try
            {
                usp_GetClientDetails result = new usp_GetClientDetails();
                await Task.Run(() =>
                {
                    result = IClientRepository.InsertClientDetails(client);
                });
                return Request.CreateResponse(HttpStatusCode.OK, new { StatusCode = HttpStatusCode.OK, Status = "Success", Data = result });
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, new { StatusCode = HttpStatusCode.InternalServerError, Status = "Failed", Data = ex.Message });
            }
        }
[HttpPost]

        public ActionResult AddClient(ClientAddModel objcltModel)
        {
            var parameters = new usp_GetClientDetails
            {
                ClientMappedTo=Convert.ToInt32(objcltModel.ClientMappedTo),
                UserName="",
                FirstName=objcltModel.FirstName,
                LastName= objcltModel.LastName,
                EmailId= objcltModel.EmailId,
                PrimaryContactNo= objcltModel.PrimaryContactNo,
                SecondaryContactNo= objcltModel.SecondaryContactNo,
                QRCode=Common.CreateQRCodeWithContact(objcltModel.PrimaryContactNo),
                AadharNo= objcltModel.AadharNo,
                PanNo= objcltModel.PanNo,
                Pincode= objcltModel.Pincode,
                City= objcltModel.City,
                IsActive=true,
                CreatedDate=DateTime.Now,
                Deposit=objcltModel.Deposite,
                Area1= objcltModel.Area1,
                Area2= objcltModel.Area2,
                FloorNo= Convert.ToInt32(objcltModel.FloorNo),
                FlatNo= objcltModel.FlatNo,
                BuildingName= objcltModel.BuildingName,
                Rate=objcltModel.Rate

            };
            var result = WebAPIGeneric.GetAPIResponse(WebAPIMethods.SaveClientDetails, parameters, Method.POST, null);
            if(result !=null)
            {
                if(result.Status=="Success")
                {
                    ViewBag.Message = "Client Added Successfully";//JsonConvert.DeserializeObject<usp_getclientdetails>(result.Data.ToString()).Message;
                }
            }
            ViewBag.Userlst = getUserList() == null ? new SelectList(string.Empty) : new SelectList(getUserList().ToList(), "UserId", "FullName");
            return View("Index");
        }
public static ResponseModel GetAPIResponse(string Url, object data, Method method,Hashtable htable)
        {
            var client = new RestClient(Common.baseUrl);
            var request = new RestRequest(Url, method);
            if(data==null && htable !=null)
            {
                foreach(DictionaryEntry entry in htable)
                {
                    request.AddParameter(entry.Key.ToString(),entry.Value.ToString());
                }
                
                //request.AddParameter("application/json", JsonConvert.SerializeObject(htable), ParameterType.QueryString);
            }
            else
            {
                request.AddJsonBody(JsonConvert.SerializeObject(data));
            }
            
            var x = client.Execute(request);
            return JsonConvert.DeserializeObject<responsemodel>(client.Execute(request).Content);
        }
public class ResponseModel {
   public int StatusCode {
      get;
      set;
   }

   public string Status {
      get;
      set;
   }

   public object Data {
      get;
      set;
   }
}
load more v
72%

i am building a project, in which when user click the buyNow button in Basket (child 2) it will pass the props back to parent where it further pass it to another child in Signin(child 3) where we call an API call(inside useEffect) to update the mysql database but it seems that the API call is called twice as in database two records are being created and in front end i got two identical invoices record but different file names.,Child 3 – Signin ,here we call the API call(using useEffect) and update the Mysql server and recieve the invoice in PDf format from backend,Any suggestion guys why i am facing this, please note if i remove the useEffect statement from the Signin it will then continuously non-stop call the API call so i think i cant remove the useEffect, other then this i cant see why it is happening. any suggestion please.,Sub Child-Useraccount then it display the items recieved from the backend-mysql nodejs

Main(APP) ___ |
   |
   _Child 1(Home) |
   _Child 2(Basket) |
   _Child 3(signin)(API triggers here) -- - Sub Child 3 - 1(useraccount)
load more v
65%

After checking other posts, I did not find an exact answer to my question but … Read more fetch request is called twice?,After checking other posts, I did not find an exact answer to my question but apparently this problem happens to others, just not exactly my problem. Every PUT, POST , DELETE Request sent from the function below is called twice. HERE is my function code that handle user changes(add,update,delete) to the UI. it’s part of ReactJS class component,For example if I want to send POST Request to create an item this item will be created twice with the same id ., Save my name, email, and website in this browser for the next time I comment.

After checking other posts, I did not find an exact answer to my question but apparently this problem happens to others, just not exactly my problem.
Every PUT, POST , DELETE Request sent from the function below is called twice.
HERE is my function code that handle user changes(add,update,delete) to the UI.
it’s part of ReactJS class component

  commitChanges({
     added,
     changed,
     deleted
  }) {
     this.setState((state) => {
        let {
           data
        } = state;
        if (added) {
           const startingAddedId = data != undefined && data.length > 0 ? data[data.length - 1].id + 1 : 0;
           var TBname = decodeURIComponent(window.location.pathname.slice(window.location.pathname.lastIndexOf(':') + 1));
           if (data == undefined) data = [{
              id: startingAddedId,
              ...added
           }];
           data = [...data, {
              id: startingAddedId,
              ...added
           }];
           fetch('http://localhost:3001/api/appo', {
                 method: 'POST',
                 headers: {
                    'Accept': 'application/json, text/plain, */*',
                    'Content-Type': 'application/json'
                 },
                 body: JSON.stringify({
                    id: startingAddedId,
                    "TBname": TBname,
                    ...added
                 })
              })
              .then((response) => this.setState({
                 data: data
              })).catch(() => console.log('POST failed'));
           this.setState({
              data: data
           })
           console.log(this.state.data);
        }
        if (changed) {
           data.map((appointment) => {
              console.log(changed[appointment._id]);
              if (changed[appointment.id] != undefined) {
                 //console.log("JSON",JSON.stringify({...appointment,...changed[appointment.id],} ) );
                 fetch('http://localhost:3001/api/appo/' + appointment.id, {
                    method: 'PUT',
                    headers: {
                       'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                       ...appointment,
                       ...changed[appointment.id],
                    })
                 }).catch(() => console.log('PUT failed'));

              }
           });
           data = data.map((appointment) =>
              changed[appointment.id] ? {
                 ...appointment,
                 ...changed[appointment.id]
              } : appointment)
           this.setState({
              data: data
           });

        }
        if (deleted !== undefined) {
           console.log(deleted);
           fetch('http://localhost:3001/api/appo/' + deleted, {
              method: 'DELETE',
              headers: {
                 'Content-Type': 'application/json'
              },
           }).catch(() => console.log('DELETE failed'));
           data = data.filter(appointment => appointment.id !== deleted);
           this.setState({
              data: data
           })
        }
        return {
           data
        };
     });
  }

Other "twice-called" queries related to "My API is called twice"