Password reset by email never makes AJAX request as intended

I inherited some code from a website developer that has since become impossible to contact and we have one issue with the site, the password reset function on the login screen.

This is from the index.js file that handles the login and forgotten password functions. The login function (not included) works fine. When entering and submitting a valid email address in our database, it doesnt seem to ever actually forward the request, instead it looks like it is, but then outputs the line “Opps!Check your internet and please try again later!”

Uses the sweetalert js framework for alerts

Original:

function forgotPass(){           
swal({   title: "Forgot Password?!",     
               text: "Please enter your registered E-mail:",     
               type: "input",   showCancelButton: true,     
               closeOnConfirm: false,   animation: "slide-from-top",     
               inputPlaceholder: "Your registered E-mail" },   
           function(inputValue){     
               if (inputValue === false)   
                   return false;        
               if (inputValue === ""){       
                   swal.showInputError("You need to enter E-mail!");       
                   return false   }        
                 
                    var recovery_email={"recovery_email":inputValue};    
                    $(".sweet-alert").addClass("hideSweet");  
                    $(".sweet-overlay").addClass("hideSweet");  
                    HoldOn.open({  
                        theme:"sk-fading-circle",  
                        message:"<h4>Processing your information! Please Wait...</h4>"  
                    });  
                      
               /*var delay=2000; //1 seconds  
    
                    setTimeout(function(){  
                      //your code to be executed after 1 seconds  
                        
                      HoldOn.open({  
                        theme:"sk-fading-circle",  
                        message:"<h4>Sending Verification code to your registered e-mail! Please Wait...</h4>"  
                    });  
                      
                    }, delay); */  
                      
                      
                    $.ajax({  
                            url: "ajax/ajax_forgot_password.php",  
                            type: "POST",  
                            data: recovery_email,  
                            success: function (data, textStatus, jqXHR) {  
                            HoldOn.close();  
                            $(".sweet-alert").removeClass("hideSweet");  
                            if(data.trim()=="success"){  
                                  
                                var email=inputValue;  
                                    swal({     
                                        title: "Verification",     
                                        text: "The verification code has been sent to your registered mail id "+inputValue+".Please enter the verification code:",     
                                        type: "input",   showCancelButton: true,     
                                        closeOnConfirm: false,   animation: "slide-from-top",     
                                        inputPlaceholder: "Enter the verification code" },   
                                        function(inputValue){     
                                            if (inputValue === false)   
                                                return false;        
                                            if (inputValue === "") {       
                                                swal.showInputError("You need to enter the verification code!");       
                                                return false   }        
                                        var verification={"verification_code":inputValue,"email":email};   
                                        var verification={"verification":verification};  
                                        $(".sweet-alert").addClass("hideSweet");  
                                            HoldOn.open({  
                                                theme:"sk-fading-circle",  
                                                message:"<h4>Verification pending!!!Please Wait...</h4>"  
                                            });  
                                                        $.ajax({  
                                                             url: "ajax/ajax_forgot_password.php",  
                                                             type: "POST",  
                                                             data: verification,  
                                                             success: function (data, textStatus, jqXHR) {  
                                                             $(".sweet-alert").removeClass("hideSweet");  
                                                                   
                                                                 HoldOn.close();  
                                                                   
                                                             if(data.trim()=="success"){  
                                                                   
                                                                  
                                                               function PasswordInput(){  
                                                                     
                                                                     
                                                                     
                                                                     swal({     
                                                                         title: "Change Password",     
                                                                         text: "Please enter new password:",     
                                                                         type: "input",  
                                                                         inputType: "password",   
                                                                         inputPlaceholder: "Enter new password",  
                                                                         showCancelButton: true,     
                                                                         closeOnConfirm: false,   animation: "slide-from-top"     
                                                                          },   
                                                                         function (inputValue){  
    
                                                                             if (inputValue === false)   
                                                                                 return false;        
                                                                             if (inputValue === "") {       
                                                                                 swal.showInputError("You need to enter new password!");       
                                                                                 return false   }    
                                                                               
                                                                             var password1=inputValue;  
                                                                               
                                                                             swal({     
                                                                                 title: "Re-Type your Password!",   text: "Re-Type your password:",     
                                                                                 type: "input",  
                                                                                 inputType: "password",    showCancelButton: true,     
                                                                                 closeOnConfirm: false,   animation: "slide-from-top",     
                                                                                 inputPlaceholder: "Re-Type your password" },   
                                                                             function(inputValue){     
                                                                                 if (inputValue === false) return false;        
                                                                                 if (inputValue === "") {       
                                                                                     swal.showInputError("You need to re-type your password!");       
                                                                                     return false   }else if(inputValue==password1){  
                                                                                                                                                                                     var password_details={"new_password":inputValue,"email":email};   
                                                                         var password_details={"password_details":password_details};  
                                                                             $(".sweet-alert").addClass("hideSweet");   
                                                                             $.ajax({  
                                                                                     url: "ajax/ajax_forgot_password.php",  
                                                                                     type: "POST",  
                                                                                     data: password_details,  
                                                                                     success: function (data, textStatus, jqXHR) {  
                                                                                     $(".sweet-alert").removeClass("hideSweet");  
                                                                                         if(data.trim()=="success"){  
    
                                                                                                            swal({  
                                                                                                                  title: "Success!",  
                                                                                                                  text: "Your password has been changed successfully!",  
                                                                                                                  type: "success",  
                                                                                                                  confirmButtonClass: "btn-success",  
                                                                                                                  confirmButtonText: "Done!",  
                                                                                                                  closeOnConfirm: false,  
                                                                                                                  closeOnCancel: false  
                                                                                                                },  
                                                                                                                function(isConfirm) {  
                                                                                                                  if (isConfirm) {  
                                                                                                                        window.open("index.php","_self");  
                                                                                                                  }  
                                                                                                                });  
    
                                                                                             }else if(data.trim()=="error"){  
                                                                                                   
                                                                                                     swal.showInputError("Opps!Please try again later!");   
                                                                                                     return false   
                                                                                             }else{  
                                                                                                     swal.showInputError("Opps!Please try again later!");   
                                                                                                     return false   
                                                                                             }  
                                                                                     },  
                                                                                     error: function (jqXHR, textStatus, errorThrown) {  
                                                                                     }  
                                                                             });  
                                                                                  
                                                                                    
                                                                                    
                                                                                     }else{  
                                                                                     swal.showInputError("Passwords doesn't match!<br>Redirecting to <strong> enter new password </Strong> in 10 seconds..");  
                                                                                       
                                                                                    //var error="Passwords doesn't match! Please try again";  
                                                                                    var delay=10000; //2 seconds  
    
                                                                                    setTimeout(function(){  
                                                                                      //your code to be executed after 1 seconds  
    
                                                                                     PasswordInput();  
    
                                                                                    }, delay);   
                                                                                      
                                                                                       
                                                                                        //exit;  
                                                                                     }  
                                                                                       
                                                                                       
                                                                                                                                                                    
    
                                                                                   
                                                                             });  
                                                                               
                                                                           
                                                                          
    
                                                                     });  
                                                                 }  
                                                                   
                                                                   
                                                                   PasswordInput();  
                                                                     
                                                                     }else if(data.trim()=="error"){  
                                                                                                   
                                                                                swal.showInputError("Verification code doesn't match.Please try again!");   
                                                                                return false   
                                                                        }else{  
                                                                                swal.showInputError("Opps!Please try again later!");   
                                                                                return false   
                                                                        }  
                                                             },  
                                                             error: function (jqXHR, textStatus, errorThrown) {  
                                                             }  
                                                     });  
                                          
                                    });  
    
                                    }else if(data.trim()=="not_exists"){  
                                          
                                                                                                   
                                        swal.showInputError("Entered E-mail ID is not exists!");   
                                        return false   
                                }else{  
                                        swal.showInputError("Opps!Check your internet and please try again later!");   
                                        return false   
                                }  
                            },  
                            error: function (jqXHR, textStatus, errorThrown) {  
                            }  
                    });   
                 
                 
           });  
             
        }

“Corrected” via validator:

function forgotPass() {
  swal({
    title: 'Forgot Password?!',
    text: 'Please enter your registered E-mail:',
    type: 'input',
    showCancelButton: true,
    closeOnConfirm: false,
    animation: 'slide-from-top',
    inputPlaceholder: 'Your registered E-mail',
  },
  (inputValue) => {
    if (inputValue === false) return false;
    if (inputValue === '') {
      swal.showInputError('You need to enter E-mail!');
      return false;
    }

    var recovery_email = { recovery_email: inputValue };
    $('.sweet-alert').addClass('hideSweet');
    $('.sweet-overlay').addClass('hideSweet');
    HoldOn.open({
      theme: 'sk-fading-circle',
      message: '<h4>Processing your information! Please Wait...</h4>',
    });

    /* var delay=2000; //1 seconds

                    setTimeout(function(){
                      //your code to be executed after 1 seconds

                      HoldOn.open({
                        theme:"sk-fading-circle",
                        message:"<h4>Sending Verification code to your registered e-mail! Please Wait...</h4>"
                    });

                    }, delay); */

    $.ajax({
      url: 'ajax/ajax_forgot_password.php',
      type: 'POST',
      data: recovery_email,
      success(data, textStatus, jqXHR) {
        HoldOn.close();
        $('.sweet-alert').removeClass('hideSweet');
        if (data.trim() === 'success') {
          var email = inputValue;
          swal({
            title: 'Verification',
            text: `The verification code has been sent to your registered mail id ${inputValue}.Please enter the verification code:`,
            type: 'input',
            showCancelButton: true,
            closeOnConfirm: false,
            animation: 'slide-from-top',
            inputPlaceholder: 'Enter the verification code',
          },
          (inputValue) => {
            if (inputValue === false) return false;
            if (inputValue === '') {
              swal.showInputError('You need to enter the verification code!');
              return false;
            }
            var verification = { verification_code: inputValue, email };
            var verification = { verification };
            $('.sweet-alert').addClass('hideSweet');
            HoldOn.open({
              theme: 'sk-fading-circle',
              message: '<h4>Verification pending!!!Please Wait...</h4>',
            });
            $.ajax({
              url: 'ajax/ajax_forgot_password.php',
              type: 'POST',
              data: verification,
              success(data, textStatus, jqXHR) {
                $('.sweet-alert').removeClass('hideSweet');

                HoldOn.close();

                if (data.trim() === 'success') {
                  function PasswordInput() {
                    swal({
                      title: 'Change Password',
                      text: 'Please enter new password:',
                      type: 'input',
                      inputType: 'password',
                      inputPlaceholder: 'Enter new password',
                      showCancelButton: true,
                      closeOnConfirm: false,
                      animation: 'slide-from-top',
                    },
                    (inputValue) => {
                      if (inputValue === false) return false;
                      if (inputValue === '') {
                        swal.showInputError('You need to enter new password!');
                        return false;
                      }

                      var password1 = inputValue;

                      swal({
                        title: 'Re-Type your Password!',
                        text: 'Re-Type your password:',
                        type: 'input',
                        inputType: 'password',
                        showCancelButton: true,
                        closeOnConfirm: false,
                        animation: 'slide-from-top',
                        inputPlaceholder: 'Re-Type your password',
                      },
                      (inputValue) => {
                        if (inputValue === false) return false;
                        if (inputValue === '') {
                          swal.showInputError('You need to re-type your password!');
                          return false;
                        } if (inputValue === password1) {
                          var password_details = { new_password: inputValue, email };
                          var password_details = { password_details };
                          $('.sweet-alert').addClass('hideSweet');
                          $.ajax({
                            url: 'ajax/ajax_forgot_password.php',
                            type: 'POST',
                            data: password_details,
                            success(data, textStatus, jqXHR) {
                              $('.sweet-alert').removeClass('hideSweet');
                              if (data.trim() === 'success') {
                                swal({
                                  title: 'Success!',
                                  text: 'Your password has been changed successfully!',
                                  type: 'success',
                                  confirmButtonClass: 'btn-success',
                                  confirmButtonText: 'Done!',
                                  closeOnConfirm: false,
                                  closeOnCancel: false,
                                },
                                (isConfirm) => {
                                  if (isConfirm) {
                                    window.open('index.php', '_self');
                                  }
                                });
                              } else if (data.trim() === 'error') {
                                swal.showInputError('Opps!Please try again later!');
                                return false;
                              } else {
                                swal.showInputError('Opps!Please try again later!');
                                return false;
                              }
                            },
                            error(jqXHR, textStatus, errorThrown) {
                            },
                          });
                        } else {
                          swal.showInputError("Passwords doesn't match!<br>Redirecting to <strong> enter new password </Strong> in 10 seconds..");

                          // var error="Passwords doesn't match! Please try again";
                          var delay = 10000; // 2 seconds

                          setTimeout(() => {
                            // your code to be executed after 1 seconds

                            PasswordInput();
                          }, delay);

                          // exit;
                        }
                      });
                    });
                  }

                  PasswordInput();
                } else if (data.trim() === 'error') {
                  swal.showInputError("Verification code doesn't match.Please try again!");
                  return false;
                } else {
                  swal.showInputError('Opps!Please try again later!');
                  return false;
                }
              },
              error(jqXHR, textStatus, errorThrown) {
              },
            });
          });
        } else if (data.trim() === 'not_exists') {
          swal.showInputError('Entered E-mail ID is not exists!');
          return false;
        } else {
          swal.showInputError('Opps!Check your internet and please try again later!');
          return false;
        }
      },
      error(jqXHR, textStatus, errorThrown) {
      },
    });
  });
}

I tried several JS validators and “corrected”.

Uncaught runtime error when running @tanstack/react-query

I am using React.js to run a simple React Query code but I am facing an error.
The code:

import { useQuery } from '@tanstack/react-query';
import Axios from "axios"


export const Home = () => {
 const { data } = useQuery(["cat"],() => {
   return Axios.get("https://catfact.ninja/fact").then((res) => res.data);
 
 });

 return (
   <h1>
     HOPE <p>{data?.fact}</p>
   </h1>
 )
}

The code above is using the public catfact api to fetch the ‘fact’ data and display it on screen.

The error:

Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions.
Please use the error stack to find the culprit call. 
More info here: 

https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object


useBaseQuery@http://localhost:3000/static/js/bundle.js:42203:13
useQuery@http://localhost:3000/static/js/bundle.js:42265:72
Home@http://localhost:3000/static/js/bundle.js:30:70
renderWithHooks@http://localhost:3000/static/js/bundle.js:20001:31
mountIndeterminateComponent@http://localhost:3000/static/js/bundle.js:23285:17
beginWork@http://localhost:3000/static/js/bundle.js:24581:20
callCallback@http://localhost:3000/static/js/bundle.js:9597:18
invokeGuardedCallbackDev@http://localhost:3000/static/js/bundle.js:9641:20
invokeGuardedCallback@http://localhost:3000/static/js/bundle.js:9698:35
beginWork$1@http://localhost:3000/static/js/bundle.js:29562:32
performUnitOfWork@http://localhost:3000/static/js/bundle.js:28810:16
workLoopSync@http://localhost:3000/static/js/bundle.js:28733:26
renderRootSync@http://localhost:3000/static/js/bundle.js:28706:11
performConcurrentWorkOnRoot@http://localhost:3000/static/js/bundle.js:28101:78
workLoop@http://localhost:3000/static/js/bundle.js:36113:46
flushWork@http://localhost:3000/static/js/bundle.js:36091:18
performWorkUntilDeadline@http://localhost:3000/static/js/bundle.js:36328:25

Standard way of converting a string to HH:MM

I am making an input field for entering HH:MM. The type of input is text. Is there a ‘standard’ way of converting any given string to HH:MM format?

(It also has to be ‘smart’, so e.g. 1234 -> 12:34, and 3 -> 03:00 (I assume). I am looking specifically for a ‘industry standard’ was of doing it, so it works same as on websites).

Thanks

moment('3', 'HH:mm').format('HH:mm')

Anything better than that?

Electron – How to point to a path outside asar generated app

I have an electron app that will be executed using a node script that will run a cron once a week. I need to execute a python file that is in a folder named dependencies and it’s created when I do the build using npm run electron:build. I’m not using the installer of the app but I’m running the exe file that is inside the win-unpacked folder that will contain the app. If I run dev mode all work fine, the file with the python script is executed without problem, but in production app the application will not recognize the dependencies folder also if it exist. How I can point correctly to the folder that is outside the asar created from the build process?

ipcMain.on('saveExtractionData', (event, ...args) => {
//Other code stuff ...  
    if( !fs.existsSync( outputDir ) ){
        console.log(`Output folder not exist. Creating folder at: ${outputDir}`);
        fs.mkdir( outputDir, (err) => {
            if( err ){
                throw err
            }
// The file and the folder exists but electron seems not recognize it with this path
            fs.readFile('dependencies/cleaner.py', (error, buffer) => {
                if(error){
                    throw error
                }
                fs.writeFileSync( path.join(outputDir, 'cleaner.py'), buffer)
            })
            fs.writeFile( path.join(outputDir, `${filename}.xlsx`), fileBuffer, (error) => {
                if( error ){
                    throw error
                }
                console.log(`Writing file ${filename}.xlsx into ${outputDir} folder...`);
                event.sender.send('resetExtractionData')
            })
        })
    } else { 
        fs.writeFile( path.join(outputDir, `${filename}.xlsx`), fileBuffer, (error) => {
            if( error ){
                console.log(error)
                throw error
            }
            console.log(`Writing file ${filename}.xslx into ${outputDir} folder...`)
            event.sender.send('resetExtractionData')
        })
    }
})

How to restore deleted mockie api URL

I am using mockie API since 3 years and today when I try to run the project I got to know that mockie URL is no longer (which I was using). Is there any ways to restore it ?

I can make a new API but I want that data which I donot have I was underimpression that this url never be deleted.

I tried to get the data from the archieve but haven’t got that as well.

React Native not running my function inside the useEffect

I am a beginner and I have been having this problem for awhile now without being able to fix it.

So basically in my application I have two contexts. One is used for authenticating the user and the other is used for fetching his data from my API. Their names being AuthContext and UserContext.

And what I want to achieve is when the user successfully logs in into his account before the homepage is shown I want to make a call to my API. So I created a function called getUserData which should work by what I have already written for the AuthContext, but for some reason it doesn’t run no matter what I tried or read I couldn’t fix this problem.

Below is my code:

UserContext.js:

import React from "react";
import { getUserData, getServiceRequests } from "../api";

export const UserContext = React.createContext();

export const UserProvider = ({ children }) => {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [userError, setUserError] = React.useState(null);
  const [serviceRequests, setServiceRequests] = React.useState(null);

  
  React.useEffect(() => {
    
    const fetchData = async() =>{
      try {
        const userToken = await SecureStore.getItemAsync('accessToken');
        console.log("Token in UserContext: " + userToken);
        const userData = await getUserData(userToken);
        console.log("userData: " + userData);
        const requests = await getServiceRequests(userToken);
        setData(userData);
        setServiceRequests(requests);
      } catch (error) {
        setUserError(error);
      } finally {
        setLoading(false);
      }
    }

    fetchData();

  }, []);

  return (
    <UserContext.Provider value={{ data, loading, userError, serviceRequests }}>
      {children}
    </UserContext.Provider>
  );
};

AuthContext.js:

import * as React from 'react';
import API_URL from '../../config.json';
import * as SecureStore from 'expo-secure-store';

export const AuthContext = React.createContext();

export const AuthProvider = ({children}) => {
    const [isLoading, setLoading] = React.useState(false);
    const [loggedIn, setLoggedIn] = React.useState(false);

    async function logout() {
        console.log('user logged out');
        await SecureStore.deleteItemAsync('accessToken');
        await SecureStore.deleteItemAsync('refreshToken');
        setLoggedIn(false);
    } // not yet ready just testing

    async function login(username, password, rememberDevice) {
        setLoading(true);  
        const url = API_URL.API_URL;      
        try {
            if (!username || !password) {
                throw new Error('Username and password are required.');
            }
    
            const response = await fetch(`${url}/login`, {
                method: 'POST',
                headers: {
                    'user-name': JSON.stringify(username),
                    'password': JSON.stringify(password),
                    'remember-device': JSON.stringify(rememberDevice),
                },
                body: '',
            });
            if (response.ok) {
                const data = await response.json();
                await SecureStore.setItemAsync('accessToken', JSON.stringify(data.access_token));
                rememberDevice == true ? await SecureStore.setItemAsync('refreshToken', JSON.stringify(data.refresh_token)) : null;
                setLoggedIn(true);
            } else {
                setLoading(false);
                throw new Error('Invalid credentials. Please try again.');
            }
        } catch (error) {
            throw error;
        } finally {
            setLoading(false);
        }
    }


    return (
        <AuthContext.Provider value={{setLoggedIn, loggedIn, login, isLoading, logout, setLoading}}>
            {children}
        </AuthContext.Provider>
    );
}

If you need me to provide more info I am happy to do so.
Again I am new to this if there is something I have missed regarding react contexts or anything I am sorry :).
Thank you.

I have tried moving the functions playing with the dependency list and everything I have seen on the internet regarding this problem and nothing has worked so far. I just want data returned from my API so that I can show it to the user.

Converting a Javascript map into an array of objects [duplicate]

I am given a map of key value pairs which I have no control over, and I need to convert them into an array of objects, but in a certain way.


    let paramArray1 = [];
    let paramArray2 = [];

    paramArray1.push({username:"test"})
    paramArray1.push({password:"test"})
    paramArray1.push({contentType:"application/json"})



    let map = new Map();
    map.set("username","test");
    map.set("password","test");
    map.set("contentType","application/json");



    for (const [key,value] of map.entries()){
      paramArray2.push({key,value})
    }



    console.log(paramArray1);
    console.log(paramArray2);

If you run that code above, you will see two outputs. Both arrays have the same items in them, but what I need is for the second array to be in the same format as the first one.

How can I convert a map of KVPs into an array without it breaking them down into key: [key], value :[value] and instead just being {key:value} like in the first array?

If you run the code you will see the problem. Thanks in advance!

I have tried changing the comma to a colon to, but that results in using the WORD key, instead of the key itself. aka the ouput for the below code is : [{key:test, key:test, key:application/json}]


    for (const [key,value] of map.entries()){
      paramArray2.push({key:value})
    }

Can’t find hander call but others are working in go

I am new to go, I recently started a new job where I work exclusively with go. I have a post request from my HTML template which calls a handler, everything is in place as it should be and it works locally when I run on MacOs, once I deploy it to the Linux server, the handler can’t seem to be found. I’ve checked everything I can think of and I cannot come right. It’s also weird that the other post calls like “genletter” work perfectly fine but “saveblperiod” does not.

It’s just so strange that it works locally without any issue but deployed it doesn’t find the handler.

script:
script 1
script 2

main.go:
enter image description here

Thanks in advance!

  • I’ve tried moving the declaration of “saveblperiod” above “genletter”.
  • I’ve checked all spelling and such
  • I’ve tried to replicate the error locally but I cannot, it works perfectly every time.

TypeScript still complaining after checking whether ref is a function

ref is a ForwardedRef<HTMLAudioElement>. So it can either be a function or an object: type ForwardedRef<T> = ((instance: T | null) => void) | MutableRefObject<T | null> | null

I’m checking if ref is a function in the if block:

const callbackRef = useCallback((node: HTMLAudioElement) => {
    if (node && typeof ref === 'function') {
      ref(node);
    } else if (ref) {
      node.volume = volume;
      ref.current = node;
    }
}, [volume]);

Then why is TypeScript still complaining in the else if block?

Property 'current' does not exist on type '((instance: HTMLAudioElement | null) => void) | MutableRefObject<HTMLAudioElement | null>'.
  Property 'current' does not exist on type '(instance: HTMLAudioElement | null) => void'.ts(2339)
any

Note: I could do (ref as MutableRefObject<HTMLAudioElement>).current, but then why would I even bother checking if ref is a function?

How can I add animation before a component re-renders and after it has re-rendered?

I have created a simple image slider that has its data stored in an array of objects. Every time I click on the previous/next button the index of the current pointing image changes and a new image and text are shown. I want to add animations before the component re-renders and after it has been rendered. Something like exit and entry of an element but in this case only state I am not removing or adding any new element, I am just changing the state of the component.

function App() {
  const [index, setIndex] = useState(0);
  useEffect(() => {
    const title = document.querySelector(".title");
    const desc = document.querySelector(".desc");
    desc.classList.remove("desc");
    title.classList.remove("reverse");
    title.classList.remove("title");
    title.clientTop;
    desc.classList.add("desc");
    title.classList.add("title");
  }, [index]);
  return (
    <div className="w-[100vw] h-[100vh] bg-slate-700 flex justify-center items-center">
      <div className="w-[60%] h-[50%] relative bg-gray-500 rounded-md">
        <div className="w-full h-full">
          <img
            src={details[index].image}
            alt="image"
            className="transition-transform max-h-full w-full rounded-md brightness-50"
          />
        </div>
        <div className="absolute top-0 w-full h-full flex flex-row m-2 px-5 gap-5 items-center">
          <Button dir="left" index={index} setIndex={setIndex} />
          <div className="flex flex-col gap-3">
            <h3 className="title text-3xl text-white aboslute transition-transform translate-x-4">
              {details[index].title}
            </h3>
            <div className="flex flex-row justify-start gap-3">
              <Tag tag={details[index].year} />
              <Tag tag="R" />
              <Tag tag="SUB" />
            </div>
            <div className="desc text-md text-white pr-56">
              {details[index].description}
            </div>
          </div>
          <Button dir="right" index={index} setIndex={setIndex} />
        </div>
      </div>
    </div>
  );
}

export default App;
const Button = ({dir, index, setIndex}) => {
  const handleClick = () => {
    const title = document.querySelector(".title");
    title.classList.add("reverse");

    setTimeout(() => {
      if (dir === "right") {
        if (index === 4) setIndex(0);
        else setIndex((curr) => curr + 1);
      } else {
        if (index === 0) setIndex(4);
        else setIndex((curr) => curr - 1);
      }
    }, 350);
  };
  return (
    <div
      className="text-white text-3xl cursor-pointer 
     "
      onClick={handleClick}
    >
      <div className="rounded-full w-10 h-10 text-center hover:bg-white hover:bg-opacity-25">
        {dir === "left" ? <>&lt;</> : <>&gt;</>}
      </div>
    </div>
  );
};

I have added animation before a render takes place by using the timeout function and for the case where the component has been rendered, I have used useEffect. I want to know whether there exists an optimal way to perform those actions. Any blog, videos, or articles are appreciated.

Why is it inaccurate to calculate fps using setTimeout?

my thoughts

  1. Call setTimeout(1000 / 60) recursively, fps increases by one each time it is called
  2. Whenever the call time exceeds 1s, record fps
  3. Clear the timer when the page is not visible, and start the timer when the page is visible.

But my recorded fps sometimes exceeds 70, why?

Below is my pseudo code

const INITIAL_FPS = 0;

export const useReportFPS = () => {
  const lastRecordTime = useRef(Date.now());
  const fps = useRef(INITIAL_FPS);
  const loopShouldRun = useRef(false);
  const timerId = useRef<NodeJS.Timer | null>(null);

  const clearTimer = useCallback(() => {
    if (timerId.current) {
      clearTimeout(timerId.current);
      timerId.current = null;
    }
  }, []);

  const fragmentation = useRef((callback: () => void) => {
    // 同一时刻内存中只有一个 fps 定时器
    clearTimer();
    timerId.current = setTimeout(() => {
      callback();
      timerId.current = null;
    }, 1000 / 60);
  });

  const handleFps = useCallback((cost: number, reportFPS: number) => {
    /** cost 时间段内经历了几个整数秒 */
    const count = Math.floor(cost / 1000);
    // 正常情况下,两次 setTimeout 调用间隔小于 2 s 上报一次 fps
    console.log('fps', reportFPS);
    // 异常情况下,两次 setTimeout 调用间隔大于 N + 1 s,后 N s 的 fps 认为是 0
    for (let i = 1; i < count; i++) {
      console.log('fps', reportFPS);
    }
  }, []);
  /** 递归调用计算和上报 fps */
  const recursiveCollectFPS = useCallback(() => {
    fragmentation.current(() => {
      // 页面不可见或标识位为 false 时停止递归调用
      if (loopShouldRun.current === false || document.hidden) {
        return;
      }
      fps.current += 1;
      const current = Date.now();
      const cost = current - lastRecordTime.current;
      if (cost > 1000) {
        handleFps(cost, fps.current);
        lastRecordTime.current = current;
        fps.current = INITIAL_FPS;
      }
      recursiveCollectFPS();
    });
  }, []);

  const startCollectFPS = useCallback(() => {
    loopShouldRun.current = true;
    fps.current = INITIAL_FPS;
    lastRecordTime.current = Date.now();
    recursiveCollectFPS();
  }, []);

  const onVisibilitychange = useCallback(() => {
    if (document.visibilityState === 'visible') {
      // 页面由不可见 -> 可见时,重新开始计算 fps
      startCollectFPS();
    } else {
      clearTimer();
    }
  }, []);

  const stopCollectFPS = useCallback(() => {
    loopShouldRun.current = false;
    clearTimer();
    document.removeEventListener('visibilitychange', onVisibilitychange);
  }, []);

  const init = useCallback(() => {
    document.addEventListener('visibilitychange', onVisibilitychange);
    startCollectFPS();
  }, []);

  useEffect(() => {
    init();
    return () => {
      stopCollectFPS();
    };
  }, []);
};

expected:
fps calculated this way <= 64

PHP form not working. On submit goes to browser window – https://thewebsite/contact.php – why? [closed]

When form is submitted on website https://sydneylactation.com.au it opens in browser address
https://sydneylactation.com.au/contact.php” with words /contact.php?!!?
I am limited with my coding expertise and have tried so many options after reading through other questions. Why is the php not sending through to email? Do I need to add javascript? I have added javascript in the form and also as a link?
I am also trying to open the thank you html page after submit?.
Below is php, html form and js
Would really appreciate your expert knowledge as I just can’t seem to progress with this although I have successfully done php web forms before?.

Kind Regards Rob

HERE is CONTACT.PHP

<?php
// define variables and set to empty values
$name = $email = $phone = $enquiry = "";

if ( $_SERVER[ "REQUEST_METHOD" ] == "POST" ) {

  if ( empty( $_POST[ "name" ] ) ) {
    $nameErr = "Name is required";
  } else {
    $name = test_input( $_POST[ "name" ] );
    // check if name only contains letters and whitespace
    if ( !preg_match( "/^[a-zA-Z-' ]*$/", $name ) ) {
      $nameErr = "Only letters and white space allowed";
    }
  }
  if ( empty( $_POST[ "email" ] ) ) {
    $emailErr = "Email is required";
  } else {
    $email = test_input( $_POST[ "email" ] );
    // check if e-mail address is well-formed
    if ( !filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
      $emailErr = "Invalid email format";
    }
  }

  if ( empty( $_POST[ "phone" ] ) ) {
    $comment = "";
  } else {
    $comment = test_input( $_POST[ "phone" ] );
  }

  if ( empty( $_POST[ "enquiry" ] ) ) {
    $comment = "";
  } else {
    $comment = test_input( $_POST[ "enquiry" ] );
  }

}

function test_input( $data ) {
  $data = trim( $data );
  $data = stripslashes( $data );
  $data = htmlspecialchars( $data );
  return $data;
}

// Create the email and send the message
$to = "[email protected]"; 
$subject = "Website Contact Form:  $name";
$body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email\n\nPhone: $phone\n\nEnquiry:\n$enquiry";
$header = "From: [email protected]\n"; 


echo htmlspecialchars( $_SERVER[ "PHP_SELF" ] );


?>

Here is FORM HTML

   <form id="contact__form" method="post" action="/contact.php" role="form">
          <div class="messages"></div>
          <div class="controls">
               <div class="row">
              <div class="col-md-10">
                   <div class="form-group">
                  <input id="form_name" type="text" name="name" class="form-control" placeholder="Name*" required="required" data-error="Your name is required." >
                  <div class="help-block with-errors"></div>
                </div>
                 </div>
              <div class="col-md-10">
                   <div class="form-group">
                  <input id="form_email" type="email" name="email" class="form-control" placeholder="Email*" required="required" data-error="Valid email is required." >
                  <div class="help-block with-errors"></div>
                </div>
                 </div>
              <div class="col-md-10">
                   <div class="form-group">
                  <input id="form_phone" type="text" name="phone" class="form-control" placeholder="Phone" >
                  <div class="help-block with-errors"></div>
                </div>
                 </div>
            </div>
               <div class="row">
              <div class="col-md-10">
                   <div class="form-group">
                  <textarea id="form_enquiry" name="enquiry" class="form-control" placeholder="Enquiry*" rows="6" required="required"  data-error="Please, leave us a message."></textarea>
                  <div class="help-block with-errors"></div>
                </div>
                 </div>
              <div class="col-md-12">
                   <input class="btn btn-large btn-primary centre mt-10" type="submit" value="Submit" >
                  <script>
document.getElementById("contact__form").addEventListener("submit",function(){
    alertIt();
    return redirect(); 
},false);
//Formvalidation
...
window.location.href = "https://www.sydneylactation.com.au/thankyou.html/“;
}
</script>

              <p>&nbsp;</p>     
                  
                 </div>
            </div>
               <div class="row">
              <div class="col-md-12">
<p class="text-muted small"><strong>*</strong> These fields are required.</p>
                 </div>
            </div>
             </div>
        </form>```
  
Here is CONTACT>JS:


$(function () {

// init the validator
// validator files are included in the download package
// otherwise download from http://1000hz.github.io/bootstrap-validator

$('#contact-form').validator();


// when the form is submitted
$('#contact-form').on('submit', function (e) {

    // if the validator does not prevent form submit
    if (!e.isDefaultPrevented()) {
        var url = "contact.php";

        // POST values in the background the the script URL
        $.ajax({
            type: "POST",
            url: url,
            data: $(this).serialize(),
            success: function (data)
            {
                // data = JSON object that contact.php returns

                // we recieve the type of the message: success x danger and apply it to the 
                var messageAlert = 'alert-' + data.type;
                var messageText = data.message;

                // let's compose Bootstrap alert box HTML
                var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
                
                // If we have messageAlert and messageText
                if (messageAlert && messageText) {
                    // inject the alert to .messages div in our form
                    $('#contact-form').find('.messages').html(alertBox);
                    // empty the form
                    $('#contact-form')[0].reset();
                }
            }
        });
        return false;
    }
})

});


failed to load config files for vite-react app on cyclic.sh

I was deploying Vite React on cyclic.sh but there’s a error :

failed to load config from /tmp/youreachedrahat-repo/client/vite.config.js
error during build:
Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@vitejs/plugin-react' imported from /tmp/youreachedrahat-repo/client/vite.config.js.timestamp-1702967721862-acd913cba0d17.mjs
    at new NodeError (node:internal/errors:405:5)
    at packageResolve (node:internal/modules/esm/resolve:890:9)
    at moduleResolve (node:internal/modules/esm/resolve:939:20)
    at defaultResolve (node:internal/modules/esm/resolve:1132:11)
    at nextResolve (node:internal/modules/esm/loader:163:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:835:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40)
    at link (node:internal/modules/esm/module_job:76:36)

folder structure

  • project
    • client
      • package.json
      • vite.config.js
    • server
    • package.json

package.json content

"scripts": {
    "dev": "concurrently "cd client && npm run dev" "cd server && npm start"",
    "build": "cd client && npm run build",
    "client": "cd client && npm run dev",
    "server": "cd server && npm start",
    "start": "npm run build && npm run server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "concurrently": "^7.6.0",
    "path": "^0.12.7",
    "vite": "^5.0.10"
  }

package.json in client

 "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "@preact/signals-react": "^1.3.8",
    "axios": "^1.6.2",
    "react-to-pdf": "^1.0.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.20.1"
  },
  "devDependencies": {
    "@types/react": "^18.2.15",
    "@types/react-dom": "^18.2.7",
    "@vitejs/plugin-react": "^4.0.3",
    "autoprefixer": "^10.4.16",
    "eslint": "^8.45.0",
    "eslint-plugin-react": "^7.32.2",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.3",
    "postcss": "^8.4.32",
    "tailwindcss": "^3.3.6",
    "vite": "^4.4.5"
  }

Vite config

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    host: true,
    strictPort: true,
    port: 8000,
    },
})

trying to deploy vite/react app on cyclic, I have it deployed on render it is working fine, but in case of cyclic there are some problem with vite apps, cyclic cannot detect vite app so I had to add vite as dependecy in package.json but then cyclic is not able to read config file for vite.

How to perform mouse actions Mouse move source webelement–> clickAndHold –> mouse move destination element with selenium4 webdriver.js

I am trying to perform below step for my senario.

  1. Move mouse pointer to source webelement
  2. Mouse click And hold on source webelement
  3. move mouse pointer to another destination webelement.

In selenium 4 “mouseDown” & “mouseMove” function are deprecated. And i tried below option to perform click and hold and move from source to destination webelement.

  1. driver.actions({ async: true}).move({ origin: sourceElement }).press().move({ origin: middleElement }).move({ origin: destinationElement }).release().perform()
  2. driver.actions({bridge: true}).move({duration: 2000,
    x: sourceLocation.x, y:sourceLocation.y}).press().
    move({ duration: 1000,
    x: destinationLocation.x, y:destinationLocation.y}).release().perform()
  3. driver.actions().move({ origin: sourceElement }).press().perform();
    await FWL.UTIL_think(4)
    await act.move({ origin: destinationElement }).release().perform()
  4. driver.actions().dragAndDrop(sourceElement,destinationElement)

All the above option didn’t worked for me.
Can anyone help me to get javascript code or another options to perform mouse “Click and hold” and move to destination webelement.

How to filter based on the user entry from array of objects

I have an array of objects

let array = [{name: "singpore"}, {name: "French Polynesia"}, {name: "poland"}, {name: "portugal"}]

I am trying to implement with below logic

 array.filter((item) => {
    return item.name.toLowerCase().includes(searchText);
  });

I am trying to search based on “po”, when i search with po i am able to get all the records in the same order.

But i need to get the results in the below order to match the first characters

Current output:

[{name: "singpore"}, {name: "French Polynesia"}, {name: "poland"}, {name: "portugal"}]

Expected output:

[{name: "poland"}, {name: "portugal"}, {name: "singpore"}, {name: "French Polynesia"}]