React Query useMutation is putting my API call state in Idle

I am using React Query to make API calls.

I have an OTP Generation API in which I am making a POST API call to generate an OTP as a response from the API I receive the status of OTP deliverance.

/* eslint-disable no-unused-vars */
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { TextField } from '../Input/TextField';
import { CustomButton } from '../Button/CustomButton';
import { MOBILE_NUMBER } from '../Common/Placeholder';
import { getOtpData } from '../../hooks/getOtp.hook';

export function MobileNumber() {
  const navigate = useNavigate();
  const [mobileno, setMobileNo] = useState('');
  const [isTermsAgree, setisTermsAgree] = useState(false);
  const [isDisplayLoader, setDisplayLoader] = useState(false);
  const [isDisplayError, setDisplayError] = useState(false);

  const { mutate, isError, isSuccess, isLoading, isIdle, data } =
    getOtpData();

  // Onchnage event for input mobile number
  const handleNumberChange = (
    e: React.ChangeEvent<HTMLInputElement>,
  ) => {
    setMobileNo(e.target.value);
  };

  // Onchnage event for Checkbox
  const TermsAgreeChange = () => {
    setisTermsAgree((current) => !current);
  };

  // onClick Event Confirm Btn //Generate OTP API call Goes Here
  const getOtp = () => {
    mutate(mobileno);
    if (isSuccess) {
      if (data?.data.otpSent) {
        console.log('Sent - true');
        navigate('/phone-otp-confirmation', {
          state: { phoneNumber: mobileno },
        });
      }
      if (data?.data.maxOtpRetriesExceeded) {
        setDisplayError(true);
      }
    }
    if (isError) {
      console.log('error');
    }
  };

  return (
    <div className="bg-grey-800 h-1/2 mt-40 flex flex-col justify-evenly font-Manrope ">
      <section>
        <div className=" flex-col flex  items-center md:items-baseline md:pl-36 ">
          <p className="  text-3xl "> Enter Mobile Number </p>
        </div>
        <div>
          <p className="text-l   flex-col flex  items-center mt-1  md:items-baseline md:pl-36 ">
            <span className=" text-gray-400  text-center ">
              Enter Mobile Number used for instant login
            </span>
          </p>
        </div>

        <div className="flex-col flex  items-center md:items-baseline md:pl-36 mt-5">
          <div className="  flex items-center sm:justify-start sm:px-0   ">
            <div>
              <div className=" flex w-18 px-3 justify-center items-center  bg-transparent rounded-bl-lg   rounded-tl-lg border text-2xl md:text-3xl  border-gray-700  h-12 md:h-16  focus:outline-none focus:bg-transparent">
                <span>+91</span>
              </div>
            </div>
            <div>
              <TextField
                width="w-48"
                height="h-12"
                padding="px-5"
                placeholder={MOBILE_NUMBER}
                maxlen={10}
                other="rounded-br-lg rounded-tr-lg  px-5 md:w-72 md:h-16"
                type="text"
                onChangeFunction={handleNumberChange}
                val={mobileno}
                error={false}
              />
            </div>
          </div>
        </div>
      </section>

      <div className="  flex-col flex mt-16 items-center md:items-baseline md:pl-36 md:mt-5  ">
        <div className="flex items-center w-72">
          <TextField
            width="w-7"
            height="h-7"
            type="checkbox"
            other="form-checkbox"
            onChangeFunction={TermsAgreeChange}
          />
          <p className="ml-3 text-sm md:text-base tracking-wide text-gray-400 font-extralight">
            I have read the OneCard{' '}
            <a
              href="http://"
              className="underline text-sm md:text-base text-gray-400"
            >
              Terms and Conditions & Privacy Policy
            </a>{' '}
          </p>
        </div>
        <div className="mt-8 ">
          <CustomButton
            clickEvent={getOtp}
            btntext="Get OTP"
            isbuttonactive={mobileno.length === 10 && isTermsAgree}
          />
        </div>
        {/* <h2>Loader</h2>
        <h2>Error</h2> */}
      </div>
    </div>
  );
}

OTP Generation hook

import { useMutation } from 'react-query';
import axios from 'axios';
import { WEB } from '../constants/constants';

interface IGetOTPResult {
  otpSent: boolean;
  maxOtpRetriesExceeded: boolean;
}

const getOTP = async (mobileNumber: string) => {
  const response = await axios.post<IGetOTPResult>(
    `${process.env.REACT_APP_URL}/`,
    {
      mobile: mobileNumber
    },
    {
      headers: {
        Authorization: '',
        'Content-Type': 'application/json',
      },
    },
  );

  return response;
};

export const getOtpData = () => {
  return useMutation(getOTP);
};

PROBLEM : As soon as I make this API call through the frontend as I click the button, it goes into isIdle state to be true.
Only the second time, I click the button, isSuccess becomes true.

However, bot the times the API call is made and I receive a 200 response!

I want to ensure my API call never enters isIdle state.

Plus, there is no significant information given about isIDle in any of react-queries documentation.

How do I go about this?

make return the largest numeric value within the array, javascript [duplicate]

This is the code I’m trying to get it to work, the problem is it just checks up to the 8th value, then disregards the rest for some reason

function a(){
    let nums = [12,11,23,22,21,34,33,55,44,43,32,41,100]
    let nam;
    let b = 1
    let a = 0

    document.body.innerHTML += "<br>a = "+nums.length

    for(let x=0;x<=nums.length;x++){
        if(nums[a]>nums[b]){
            nam = nums[a]
            b++
        }else{
            nam = nums[b]
            a++
        }
        document.body.innerHTML += "<br>a = "+nums[a]
        document.body.innerHTML += "<br>b = "+nums[b]
        document.body.innerHTML += "<br>nam = "+nam
    }
}
a()

Switching between SQL Quarries

I know this is not the typical question that StackOverflow should handle but I need people’s ideas for this.

I’m currently learning PHP for web development and I’m working with SQL and a bit of data from my company (Confidential and I’m unable to show it). I have 2 different quarries currently written and I want to use a switch or a button (don’t know which is better) to switch between the 2 quarries in the back to display different data on the screen.

What are the best ways of doing this? I would be very appreciative if someone can give me a few code snippets on how to do this.

Thanks

Stop VSCode adding “endregion” autocompletion when pressing “enter” key

I am editing JSX code in .js files, and since two days (i don’t know why), each time I press ENTER key in VS Code to add a new empty line, then VS Code display this:

This is what VS code do

If I press ENTER again, then VS Code add “//#endregion” in my code.

But the point is, I don’t want this, I just want to jump a line, I don’t want VS Code to write this for me.

Do you know why VS Code has this behavior now, and how I can avoid VS Code doing this ?

Thank you very much

Is there a method to update a data object from vue when the database updates?

I’m making a web app that allows users to create an account and then join a room. Inside the room they can click a button and essentially allows them to pick who they are gonna give a gift to randomly. The problem I’m having is how do I update a data object from vue if the database updates for all users. What I mean is if a another user joined a room, the new user has the updated data object but all the other users who came before him will have the outdated data object. So what I’m essentially asking is how would vue update a data object if the database updates.

And by data object I mean something like this

data() {
 return {
  room: { name: "room", users: [] }
 }
}

Does the update() lifecycle hook do that? or computed()?
And before anyone answers, remember I need it to update to ALL the users that joined the room.

I’m using vue2 since I’m using vuetify

Must use import to load ES Module while updating angular

I ran into this problem while trying to upgrading from angular 6 to 8, whenever i try to ng serve or ng build i get the following error:

its been so fustrating, i’ve tried adding the “type”:”modules” to my package.json, trying renaming those files with the error to .cjs (then it doesnt even find the files because they are looking for the .js version)

i think the problem here is that the files with the error are inside node_modules?

i’ve tried deleting node_modules and doing NPM install but it was the same

require() of ES modules is not supported.
require() of W:sites****[email protected] from W:sites****CreditoConsumonode_modules@ngtoolswebpacksrcangular_compiler_plugin.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from W:sites****[email protected].```



Digits being added instead of numbers [duplicate]

I am using Svelte and trying to make a game where when you click it will add a number, it works fine at first, but I make sure to save there data, for now im just storing it in localeStorage, now here is when the problem comes in. When I click the button now it will add a digit instead of adding just one to the number.

This is a bit of a weird question because it is oddly specific. I have looked up multiple things, and I cant seem to find this question has been asked before so I am now asking, Ive spent about 30 minutes researching, and nothing has came up.

What I think is happening is that the localeStorage is storing it as a string and not a number even though I have it in a :number to make sure that the variable will always be a number.

let clicks: number = 0;
  let cps: number = 0;
  let cpc: number = 1;
  let cm: number = 1.00;

  function handleClick() {
    const newClicks = cpc * cm;
    clicks += newClicks;
    window.localStorage.setItem('clicks', clicks);
  }

  window.addEventListener("load", function() {
    let sClicks = window.localStorage.getItem('clicks');
    clicks = sClicks;
}, false); 

this is inside of my <script> and in my html I have a simple <button on:click={handleClick}>{clicks}</button>

Im going to try to describe the problem a little more detail if you dont understand, when ever I click the button it will add one so it will go like this,
1, 2, 3, 4, 5, 6 now when I refresh the same number is there however when I click now it will go
61, 611, 6111, 61111, 611111 and so on. And it will still update the value in the localeStorage to be 6111 for example.

Thank you for any help.

connect online existing database with node js

I have a database an online link to the database and I want to connect it to node js and fetch data in my javascript project.
https://unplausible-trouble.000webhostapp.com/editor-4.8.1-mysql.php
And a Data in this database is related to this project.
https://visjs.github.io/vis-timeline/examples/timeline/other/groupsPerformance.html
I want to connect my project with the database which exists online.

Why does .join Method not work on my array?

I want to use JS to create a XML file, for thus I want to print my array that contains the snippets of my XML file without commas but .join() doesnt work

// creating of the XML snippets “<test” and “>”

let testArray = [];
var XML = new XMLWriter();
XML.BeginNode("test");
XML.EndNodeSingle();

// pushing into array and using .join()

testArray.push(XML.XML);

testArray = testArray.join(' ');

// trying to print array into a textarea

document.getElementById('xml').innerHTML = testArray;

// returns <test,>” but <test> is needed

Regex to validate comma separated string with special characters [closed]

I want a common regex to validate below comma separated strings.

input: 10.25.02.12:19092,10.25.02.12:29092,10.25.02.12:39092,10.25.02.12:49092 => should pass

input: at-sdf-dfds-in,at-dfd-in-32,at-wtn-df-df-dfd-in => should pass

input: localhost:19092,localhost:29092,localhost:39092,localhost:49092 => should pass

input: strg1,strg2,strg3 => should pass

input: localhost:19092, => should fail as comma at the end

Please help in this. Thanks in advance.

Why does this function prompt twice?

I’ve written a bookmarklet for clicking a controllable amount of times on a HTML element (for clicker games, the like). However, when I run it, it prompts “How many times do you want to click?” twice.

To the best of my knowledge, the second prompt doesn’t do anything. Is there a way I can get rid of it?

Code:

javascript:
var clicked = false
document.onclick= function(event) {  
    if (!clicked) {
      var target= 'target' in event? event.target : event.srcElement;

      var clickamount= parseInt(prompt("Enter time to click "+target.id))-1;

      for (let i = 0; i < clickamount; i++) {
          target.click();
      }
      clicked = true
    }
    
};