Why does useActivePage() in React MUI Toolpad example return null?

I need to add slots to a PageContainer, specific to each page, so I need to get the title of the page first. I’m following example in MUI Toolpad for dynamic routes in PageContainer component:

https://next.mui.com/toolpad/core/react-page-container/

It looks like this:

export default function Example() {
  const params = useParams<{ id: string }>();
  const activePage = useActivePage();
  invariant(activePage, 'No navigation match');

  const title = `Item ${params.id}`;
  const path = `${activePage.path}/${params.id}`;

  const breadcrumbs = [...activePage.breadcrumbs, { title, path }];

  return (
    <PageContainer title={title} breadcrumbs={breadcrumbs}>
      ...
    </PageContainer>
  );
}

But when I try to do something similar, like this:

 const activePage = useActivePage();     //returns null
 console.log("Nav: activePage=", activePage);   
 invariant(activePage, 'No navigation match');
 const path = activePage ? `${activePage.path}` : '';   //returns empty string
 console.log("Nav: path=", path);  

 return (
   <ReactRouterAppProvider
     navigation={NAVIGATION}
     branding={BRANDING}
   >
   <DashboardLayout>
     <PageContainer>
       <Outlet />
     </PageContainer>
   </DashboardLayout>    
   </ReactRouterAppProvider>
 )

useActivePage() returns null. Has anybody else run into this issue and got it to work?

Click Event Does not Trigger when holding down a key

I have a weird problem that is happening only on Chrome Windows 10, but not on Windows 11 or OSX. Im using Electron (nothing more than Javascript).

My goal is, when I click inside an iframe, I need to be able to detect if either “S” or “B”is being held down. The code below works perfectly fine on latest Chrome (OSX and Windows 11). For some weird reason, I cant get the console log click to print and execute the function. It seems that when either “s” or “b” is held down, the clickEventHandler does not trigger (it does not print the console log message) on Windows 10.

window.is_key_down = (() => {
    window.keystate = {};
    window.ifra = document.querySelector('iframe');
    ifra.contentDocument.body.addEventListener('keyup', (e) => keystate[e.key] = false);
    ifra.contentDocument.body.addEventListener('keydown', (e) => keystate[e.key] = true);
    return (key) => keystate.hasOwnProperty(key) && keystate[key] || false;
})();

var clickEventHandler = function(){
    console.log('Click On Iframe Detected')
    //Can also Replace with is_key_down("s")
    if(keystate.s){
        window.placeAD("side1")
        //keystate={}
    }
    //Can also Replace with is_key_down("b")
    if(keystate.b){
        window.placeAD("side2")
        //keystate={}
    }
}

var iframe = document.querySelector('iframe');
iframe.contentDocument.body.addEventListener('click',clickEventHandler);

I am more than puzzled, so perhaps a different approach to work on both would be great.

I have tried many different combinations and other tricks, but the clickEventHandler is not triggered if “s” or “b” are being held down when clicking. If no keys are being held down, the console log prints just fine.

Thanks in advance!!

Why is my pet state only updating hunger in React, and not boredom or energy?

I’m building a simple React app where I have a pet with properties like hunger, boredom, and energy. I want to update these properties at different intervals (hunger every 5 seconds, boredom every 8 seconds, and energy every 10 seconds).

However, while the hunger stat updates correctly, the boredom and energy stats do not. I’m using setInterval to update these values, but it seems like only hunger is being updated.

Here’s the relevant code:

import { useEffect, useState } from "react";
import { Pet } from "./types/pet";

function App() {
  const [pet, setPet] = useState<Pet | null>(null);

  useEffect(() => {
    // Load pet from localStorage or create a new pet
    const savedPet = localStorage.getItem("pet");
    if (savedPet) {
      try {
        const parsedPet = JSON.parse(savedPet) as Pet;
        setPet(parsedPet);
      } catch (error) {
        console.error("Error parsing saved pet:", error);
        createNewPet();
      }
    } else {
      createNewPet();
    }
  }, []);

  const updatePet = (updateFn: (currentPet: Pet) => Partial<Pet>) => {
    setPet((prevPet) => {
      if (!prevPet) return null;
      const updatedPet = { ...prevPet, ...updateFn(prevPet) };
      localStorage.setItem("pet", JSON.stringify(updatedPet));
      return updatedPet;
    });
  };

  useEffect(() => {
    if (!pet) return;

    const hungerInterval = setInterval(() => {
      updatePet((pet) => ({ hunger: Math.min(pet.hunger + 1, 100) }));
    }, 5000);

    const boredomInterval = setInterval(() => {
      updatePet((pet) => ({ boredom: Math.min(pet.boredom + 1, 100) }));
    }, 8000);

    const energyInterval = setInterval(() => {
      updatePet((pet) => ({ energy: Math.max(pet.energy - 1, 0) }));
    }, 10000);

    return () => {
      clearInterval(hungerInterval);
      clearInterval(boredomInterval);
      clearInterval(energyInterval);
    };
  }, [pet]);

  return (
    <div>
      <p>Hunger: {pet.hunger}%</p>
      <p>Boredom: {pet.boredom}%</p>
      <p>Energy: {pet.energy}%</p>
    </div>
  );
}

export default App;

What I’m experiencing:

  • The hunger stat updates correctly every 5 seconds.
  • The boredom and energy stats do not update as expected, even though their intervals are set up in the same way.

What I’ve tried:

  • I’ve checked the intervals and they seem to be correct.
  • I tried updating the state with functional updates to ensure the latest state is used, but still, only hunger updates.

Does anyone know why only the hunger stat is updating, and what I can do to fix this?

How to dynamically import components with fallback in React 19 (alternative to @loadable/component)?

Issue:

I’m trying to use @loadable/component for dynamic imports in my React project, but I get the following error when running:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! Found: [email protected]
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.3.0 || ^17.0.0 || ^18.0.0" from @loadable/[email protected]

It seems @loadable/component does not yet support React 19.

Example:

In my component, I currently use:

import loadable from '@loadable/component';

const EmojiPickerComponent = loadable(() => import('./EmojiPicker'), {
  fallback: <p id="loading">Loading...</p>
});

This no longer works with React 19.


Question:

What is the recommended way to achieve the same dynamic import functionality with fallback in React 19?
Is there any official or community-recommended alternative to @loadable/component for React 19?


Example use case:

const EmojiPickerComponent = ??? // What should I use here?

{showEmojiContainer && (
  <EmojiPickerComponent
    onEmojiClick={(event, emojiObject) => {
      setMessage((prev) => `${prev} ${emojiObject.emoji}`);
    }}
  />
)}

Environment:

  • React: 19.0.0
  • Node.js: 22.14.0
  • npm: 10.9.2

Any suggestions or guidance would be appreciated!

How do I mimic grass being but using JavaScript and CSS?

I’ve been practicing animation in JavaScript and CSS and there’s a transition I want to do that goes from dark green to a light green to mimic grass being cut but the animation goes too quick and doesn’t properly track the lawn mowers position, so I was wondering what I did wrong. I think it has to do with the ‘progress’ variable but I’m not sure.

Also I’m not sure if the whole creating a strip of grass in JavaScript is the best approach to this animation.

Any help would be appreciated.

const grass = document.getElementById('grass');
const lawnMower = document.getElementById('lawnMower');

// Function to create a vertical strip of grass that transitions color
function createGrassStrip(x, width) {
    const strip = document.createElement('div');
    strip.style.position = 'absolute';
    strip.style.top = '0';
    strip.style.left = `${x}px`;
    strip.style.width = `${width}px`;
    strip.style.height = '100%';
    grass.appendChild(strip);
    return strip;
}

// Function to update the grass strip color based on lawn mower position
function updateGrassStrip(strip, mowerPosition) {
    const viewportHeight = window.innerHeight;
    const progress = (viewportHeight / mowerPosition) * 10;

    // Transition from dark green to light green BELOW the lawn mower
    const darkGreen = '#388E3C';
    const lightGreen = '#8BC34A';
    strip.style.background = `repeating-linear-gradient(0deg, ${darkGreen}, ${darkGreen} ${progress}%, ${lightGreen} ${progress}%, ${lightGreen} 100%)`;
}

// Create a grass strip for the lawn mower's path
const mowerWidth = 100; // Width of the lawn mower
const mowerX = (window.innerWidth - mowerWidth) / 2; // Center the strip
const grassStrip = createGrassStrip(mowerX, mowerWidth);

// Update grass strip color on every animation frame
function animate() {
    const mowerPosition = lawnMower.getBoundingClientRect().top;
    updateGrassStrip(grassStrip, mowerPosition);
    requestAnimationFrame(animate);
}

// Start the animation
animate();
body, html {
    margin: 0;
    padding: 0;
    height: 100%;
    overflow: hidden;
    font-family: Arial, sans-serif;
}

.lawn {
    position: relative;
    width: 100%;
    height: 100vh;
    background-color: #4CAF50;
    overflow: hidden;
}

.grass {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #388E3C;
    );
}

.lawn-mower {
    position: absolute;
    top: 0;
    left: 50%;
    width: 100px;
    height: 50px;
    background-color: #FF5722;
    border-radius: 10px;
    transform: translateX(-50%);
    animation: mow 2.5s linear;
}

@keyframes mow {
    0% {
        top: 0;
    }
    50% {
        top: 50%;
    }
    100% {
        top: 100%;
    }
}

.content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    color: white;
    z-index: 1;
}
<div class="lawn">
    <div class="grass" id="grass"></div>
    <div class="lawn-mower" id="lawnMower"></div>
</div>
<div class="content">
</div>

Producing the same ciphertext in React Native and Flutter

I am trying to produce identicall cipher texts in a Java Script app and a Flutter app. I have tried to use the AES algorithm in both ECB and CBC mode using the CryptoJS library and encrypt.dart. I have used the same explicit keys and IVs in both apps, aswell as the same padding scheme but the cipher output is never the same, when using larger input data the ciphertexts differ quite alot in size. The input data is the same .json file in both applications.

Java Script:

   const jsonData = fs.readFileSync(inputFile, "utf8");

   const sKey = "123";
   const sIV = "123";

   const key = CryptoJS.enc.Utf8.parse(sKey.padEnd(32, " "));
   const iv = CryptoJS.enc.Utf8.parse(sIV.padEnd(16, " "));

   const encryptedData = CryptoJS.AES.encrypt(jsonData, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
   });

   const cipherText = encryptedData.toString();

Flutter:

      String jsonData = await loadAsset('assets/dataStorage/smallData.json');
      
      final String sKey = "123";
      final String sIV = "123";

      final key = encrypt.Key(Utf8Encoder().convert(sKey.padRight(32, ' ')));
      final iv = encrypt.IV.fromUtf8(sIV.padRight(16, ' '));

      final encrypter = encrypt.Encrypter(encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: 'PKCS7'));

      final encrypted = encrypter.encrypt(jsonData, iv: iv);

      String cipherText = encrypted.base64;

I wish to know why the ciphers differ so much, am I doing anything wrong or is it not possible to prduce identical ciphertexts using these libraries/frameworks?

odoo18 migration: how to solved messed css style css website?

Working locally with a migrated database from odoo16 to odoo18, i can get my website but the css style are not loaded correctly (messed display). I get this error in the browser console:

"Could not get content for /_custom/web.assets_frontend/website/static/src/scss/options/user_values.scss.                       web.assets_frontend_lazy.min.js:3966:395

and the corresponding js lines in web.assets_frontend_lazy.min.js:3966:395:

translationIsReady.then(
          () => {
            for (const asset of assets) {
              let cssRules;
              try {
                cssRules = asset.cssRules;
              } catch {
                continue;
              }
              const lastRule = cssRules?.[cssRules?.length - 1];
              if (lastRule?.selectorText === 'css_error_message') {
                const message = _t(
                  'The style compilation failed. This is an administrator or developer error that must be fixed for the entire database before continuing working. See browser console or server logs for details.'
                );
                notification.add(message, {
                  title: _t('Style error'),
                  sticky: true,
                  type: 'danger',
                });
                console.log(
                  lastRule.style.content.replaceAll('\a', 'n').replaceAll('\*', '*').replaceAll(`\"`, `"`)
                );
              }
            }
          }
        );
      },
    };

enter image description here

React 19 hook – useActionState with checkbox

I have a simple React app.

It has one checkbox.

The checkbox value is sent to the server, which validates the value and sends a response. The response should update the React form state.
In the simplified example below, the “server” just “echoes” the checkbox value.

Here is code:

import React, { useActionState, useEffect, useState } from "react";

async function handle(
  currState: boolean,
  queryData: FormData
): Promise<boolean> {
  // emulate server validation
  const response = await (async () => {
    await new Promise((resolve) => {
      setTimeout(resolve, 500);
    });
    return queryData.get("foo") === "on";
  })();
  return response;
}

function Checkbox({ state }: { state: boolean }): React.JSX.Element {
  const [value, setValue] = useState(state);
  useEffect(() => {
    if (typeof state === "boolean") {
      setValue(state);
    }
  }, [state]);
  return (
    <>
      <label htmlFor="foo-id">Foo</label>
      <input
        id="foo-id"
        type="checkbox"
        checked={value}
        onChange={() => {
          setValue(!value);
        }}
        name="foo"
      />
    </>
  );
}

function App(): React.JSX.Element {
  const [formState, formAction, isPending] = useActionState(handle, true);

  return (
    <div>
      <form action={formAction} noValidate>
        <Checkbox state={formState} />
        <button style={{ display: "block" }} disabled={isPending} type="submit">
          Send
        </button>
      </form>
    </div>
  );
}

export default App;

Here is working example
https://codesandbox.io/p/sandbox/8dsr6y

When the checkbox is checked and the “server” responds with true, everything works fine. The checkbox stays checked.

But why, when I uncheck the checkbox, then click the send button, does the checkbox automatically get checked again, even if the “server” responds with false?

I have no idea why it behaves this way.

Websocket connection is closing in ios when app is in background React.js

I am facing problem ,when my react app is running in background in ios device, my websocket connection is breaked .It is neccessasry for my application that my socket connection should not break,Below is my code ,I have made websocket connection after my background api,it is working fine in case of andriod but fails in ios device ,what can be possible reasons for this?



import { useNavigate } from 'react-router-dom';
import { HeaderforLoginOtpSocket ,HeaderforVerifyOtpSocket,UserLinkedAccountHeader,ConsenthandleStatusCheck} from '../helper/HeaderMakerforSocket';
import { toast} from 'react-toastify';
import { LoginOtpVerify,SubmitConsent ,ConsentApprove} from '../Apiservices';
import { useMyContext } from '../../AppContext';
import { Loader } from '../helper/Loader';
import mixpanel from 'mixpanel-browser';
import OtpInput from "react-otp-input";
mixpanel.init(process.env.REACT_APP_MIXPANEL_TOKEN, { debug: true });

export default function Verifyopt({Error}) {
const [LoginConnectionData,SetLoginConnectionData]=useState();
const [one,setone]=useState("");
const [two,settwo]=useState("");
const [three,setthree]=useState("");
const [four,setfour]=useState("");
const [five,setfive]=useState("");
const [six,setsix]=useState("");
const [Pendingrequest,SetPendingRequest]=useState(false);
const [count, setCount] = useState(0);
const [time,settime]=useState(60);
const [border_style,Setstyle]=useState()
const inp1 = useRef(null);
const inp2 = useRef(null);
const inp3 = useRef(null);
const inp4 = useRef(null);
const inp5 = useRef(null);
const inp6 = useRef(null);
const numberRegex=/^-?d+$/;
// const inputRefs = [inp1,inp2,inp3,inp4,inp5,inp6];
// const numInputs = inputRefs.length;

const { Storage,SetStorage } = useMyContext();
const SubmitConsentBeforeSocketConnection=()=>{
  SetPendingRequest(true);
  SubmitConsent().then((response)=>{
    if(response.status==200)
    {
      
      mixpanel.identify(response?.data?.user_id);
      mixpanel.people.set({$name:response?.data?.user_id})
      mixpanel.track("Viewed_BS_Verified_OTP", {
        Platform: window.innerWidth > 991 ? "web" : (localStorage.getItem('platform')?localStorage.getItem('platform'):'M-site'),
        user_type:localStorage.getItem('user_type')
      });
     SetPendingRequest(false);
      HandleSocketConnection(response?.data);
    }
    
  }).catch((error)=>{
    // console.log(error);
    SetPendingRequest(false);
   
    if(error?.response?.status==401)
    {
    toast.error("Your session is expired. Please try again");
    setTimeout(()=>{

      localStorage.clear();
      window.open(process.env.REACT_APP_CLOSING_URL, "_self");

    },1000)
  }else{
    Storage.internalservererror=true;
     SetStorage(Storage);
    navigate('/finalresult');
  }
 
   
  })
}
const [otp,setOtp]=useState('');

useEffect(() => {  
  
 


// window.addEventListener("beforeunload", function (event) {
  
//       window.opener = null;
// window.open('', '_self');
// window.close();
// });

SubmitConsentBeforeSocketConnection();


const previousPage = document.referrer;
window.history.pushState(null, null, window.location.href);
window.onpopstate = function () {
  window.history.pushState(null, null, window.location.href);
}
return () => {
  window.onpopstate = null;
};

}, [])



// console.log(Storage)


const HandleSocketConnection=(userData)=>{
     const socket = new WebSocket(process.env.REACT_APP_WEB_SOCKET_URL); 

      
     socket.onopen = () => {
        // console.log('WebSocket connection established.');
        HandleMakeConnection(socket,userData);
      };
      
      socket.onmessage = (event) => {
        const receivedMessage = JSON.parse(event.data);
        // console.log("DATA  ",receivedMessage)
      };
      
  
localStorage.setItem("socket",socket);
      socket.onclose = () => {
        // console.log('WebSocket connection closed.');
        toast.error("Your session is expired. Please try again");
     
        setTimeout(()=>{
          settime(0);
          window.location.href=`/?token=${localStorage.getItem('access_token')}&platform=${localStorage.getItem('platform')}&user_type=${localStorage.getItem('user_type')}` ;

        },1000)
   

      };
  }


 

 
  const HandleMakeConnection=(Socketconnnection,userData)=>{
    // console.log("sdjnsnlsdljnsd");
    // const Socketconnnection=Storage.Socketconnnection;
    // const userData=Storage.userData;
    if(!userData)
    {
      setTimeout(()=>{
 window.opener = null;
      window.open('', '_self');
      window.close();
      },[2000])
     
    }
    else{

    const message ={
      header: HeaderforLoginOtpSocket,
      payload:{
        username: userData?.username,
        mobileNum: userData?.mobileNum,
        handleId: userData?.consentHandle},
       };
       const mydata=JSON.stringify(message);
     
          Storage.Socketconnnection=Socketconnnection;
          Storage.userid = userData?.username;
          Storage.consentHandle = userData?.consentHandle;
          Storage.mobilenumber = userData?.mobileNum;
          Storage.userData=userData;
          SetStorage(Storage);


       Socketconnnection.send(mydata);
       Socketconnnection.onmessage = (event) => {
        const receivedMessage = JSON.parse(event.data);
        SetLoginConnectionData(receivedMessage);
        if(receivedMessage?.payload?.status=='FAILURE')
        {
          
          setTimeout(()=>{
            if(receivedMessage?.payload?.message=='Consent request not in PENDING status')
            {
             
              // Storage.finalConsentApproval = true;
              // SetStorage(Storage);
              // navigate("/finalresult");

              HandleSubmitConsentApprovaltoBackend(userData?.username,userData?.consentHandle);

            }else{
              navigate("/finalresult");
                    // window.location.href=`/?token=${localStorage.getItem('access_token')}` ;
            }
          },1000)
        }
      
      };
    }
  }


  const HandleSubmitConsentApprovaltoBackend = (userid,consentHandle) => {
  SetPendingRequest(true);
    ConsentApprove(consentHandle, userid)
      .then((response) => {
        if (response.status == 200) {
          
         if(response?.data?.status=='SUCESS')
         {
          SetPendingRequest(false);
          Storage.finalConsentApproval = true;
          Storage.consentpending=false;
          SetStorage(Storage);
          navigate("/finalresult");
         }
         else if(response?.data?.status=='FAILED')
         {
          SetPendingRequest(false);
          Storage.finalConsentApproval = false;
          Storage.consentpending=false;
          SetStorage(Storage);
          navigate("/finalresult");
         }
         else{
          SetPendingRequest(false);
          Storage.finalConsentApproval = false;
          Storage.consentpending=true;
          SetStorage(Storage);
          navigate("/finalresult");
        }
       

        }
      })
      .catch((error) => {
        navigate("/finalresult");
      });
  };



  
  const handleConsentStatus = (sessionid) => {
    
    ConsenthandleStatusCheck.sid = sessionid;
   
    const message = {
      header: ConsenthandleStatusCheck,
      payload: {
      handleId: Storage?.consentHandle, 
      },
    };


    const Socketconnnection = Storage?.Socketconnnection;
    if(!Socketconnnection)
    {
      window.location.href=`/?token=${localStorage.getItem('access_token')}&platform=${localStorage.getItem('platform')}&user_type=${localStorage.getItem('user_type')}` ;
    }
    else{
        Socketconnnection.onclose = () => {
          localStorage.removeItem('insession');
          toast.error("Your session is expired. Please try again");
            setTimeout(() => {
              window.location.href=`/?token=${localStorage.getItem('access_token')}&platform=${localStorage.getItem('platform')}&user_type=${localStorage.getItem('user_type')}` ;
                }, 1000);
            };
            
            Socketconnnection.send(JSON.stringify(message));
            
            Socketconnnection.onmessage = (event) => {
                const receivedMessage = JSON.parse(event.data);
                // HandleSubmitConsentApprovaltoBackend();
               if(receivedMessage?.payload?.status=="SUCCESS")
               {

                if(receivedMessage?.payload?.handleStatus=="READY")
                {
                  
                  Storage.finalConsentApproval = true;
                  SetStorage(Storage);
                  navigate('/finalresult');
                  
                }
                else if(receivedMessage?.payload?.handleStatus=='PENDING'){
                  // handleConsentStatus (sessionid);
                  HandleUserLinkedAccounts(sessionid);
                }
                else{
                  HandleUserLinkedAccounts(sessionid);
                }
              }else{

                navigate('/finalresult');
              }

        };
      }
    }

  const HandleUserLinkedAccounts=(sessionid)=>{
    UserLinkedAccountHeader.sid=sessionid;
    const message={
     header:UserLinkedAccountHeader,
     payload:{
         userId: Storage?.userid
     }
    };
    const Socketconnnection=Storage.Socketconnnection;
    if(!Socketconnnection)
    {
      window.location.href=`/?token=${localStorage.getItem('access_token')}&platform=${localStorage.getItem('platform')}&user_type=${localStorage.getItem('user_type')}` ;
    }
    else{
    Socketconnnection.onclose=()=>{
      toast.error("Your session is expired. Please try again");
     localStorage.removeItem('insession');
     setTimeout(()=>{
      window.location.href=`/?token=${localStorage.getItem('access_token')}&platform=${localStorage.getItem('platform')}&user_type=${localStorage.getItem('user_type')}` ;
     },1000)
    }
    Socketconnnection.send(JSON.stringify(message));

    Socketconnnection.onmessage = (event) => {
     const receivedMessage = JSON.parse(event.data);
   if(receivedMessage.payload.LinkedAccounts?.length>0)
   {
    // console.log("redirected");
    // navigate('/selectbank');
    navigate('/confirmconsent');
   }
   else{
    navigate('/selectbank');
   }
     
   };
}

 }
  const HandleVerifyOtp=(otp)=>{

    const message ={
      header: HeaderforVerifyOtpSocket,
      payload:{
        otpReference:LoginConnectionData?.payload?.otpReference,
        otp:otp
      },
       };
       const mydata=JSON.stringify(message);
       const Socketconnnection=Storage.Socketconnnection;

       if(!Socketconnnection)
       {
        toast.error("Your session is expired. Please try again");
       window.location.href=`/?token=${localStorage.getItem('access_token')}&platform=${localStorage.getItem('platform')}&user_type=${localStorage.getItem('user_type')}` ;
       }
      else
      {
       Socketconnnection.onclose=()=>{
        toast.error("Your session is expired. Please try again");
        localStorage.removeItem('insession');
        setTimeout(()=>{
          window.location.href=`/?token=${localStorage.getItem('access_token')}&platform=${localStorage.getItem('platform')}&user_type=${localStorage.getItem('user_type')}` ;
        },1000)
       }
       SetPendingRequest(true);
       Socketconnnection.send(mydata);
       Socketconnnection.onmessage = (event) => {
        const receivedMessage = JSON.parse(event.data);
        // console.log(receivedMessage.payload.status);
        Storage.sessionid=receivedMessage?.header?.sid;
        // console.log(Storage);
        SetStorage(Storage);
        SetPendingRequest(false);
        if(receivedMessage?.payload?.status=='SUCCESS')
        {
          localStorage.setItem('insession',true);
          // console.log(receivedMessage.payload);
          localStorage.setItem('sessionid',receivedMessage?.header?.sid);
          handlegiveLoginOtpVerifyInfo(receivedMessage);
        }
        else{
          setone("");
          settwo("");
          setthree("");
          setfour("");
          setfive("");
          setsix("");
          setOtp('');
          toast.error(receivedMessage?.payload?.message);
          if(receivedMessage?.payload?.message=='Maximum retries exceeded. Please re-initiate otp.')
          {
            settime(0);
         
          }
        }
      };
    }
  }
const handleResend=(e)=>{
  mixpanel.track("Interacted_BS_Verified_OTP", {
    "Clicked on": "Re-send OTP",
    Platform: window.innerWidth > 991 ? "web" : localStorage.getItem('platform')?localStorage.getItem('platform'):'M-site',
    user_type:localStorage.getItem('user_type')
  });
e.preventDefault();
if(time>0)
{
  return ;
}
setOtp('');
settime(60);
HandleMakeConnection(Storage.Socketconnnection,Storage.userData);
  }
const handlegiveLoginOtpVerifyInfo=(receivedMessage)=>{
 SetPendingRequest(true);
LoginOtpVerify({data:receivedMessage}).then((response)=>{
if(response.status==200)
{
  SetPendingRequest(false);
  handleConsentStatus(receivedMessage?.header?.sid);
  // HandleUserLinkedAccounts(receivedMessage.header.sid);

}
}).catch((error)=>{
  SetPendingRequest(false);

  if(error?.response?.status==401)
  {
  toast.error("Your session is expired. Please try again");

  setTimeout(()=>{
    localStorage.clear();
    window.open(process.env.REACT_APP_CLOSING_URL, "_self");
  },1000)

}else{
  Storage.internalservererror=true;
  SetStorage(Storage);
  navigate('/finalresult');
}

})
  }

  const handlesubmit=(e)=>{
    mixpanel.track("Interacted_BS_Verified_OTP", {
      "Clicked on": "Verify",
      Platform: window.innerWidth > 991 ? "web" : localStorage.getItem('platform')?localStorage.getItem('platform'):'M-site',
      user_type:localStorage.getItem('user_type')
    });
      e.preventDefault();
    //  console.log(otp);
      HandleVerifyOtp(otp);
  }
  

const navigate=useNavigate();
useEffect(() => {
    const myInterval= setInterval(handletime, 1000);
     return ()=> {
         clearInterval(myInterval);
       };
 }, [time]);



    const handletime=()=>{
        if(time>0)
        {
        settime(time-1);
        }
    }


 
  
    const handleredirect=(e)=>{
      mixpanel.track("Interacted_BS_Verified_OTP", {
        "Clicked on": "T&C",
        Platform: window.innerWidth > 991 ? "web" : localStorage.getItem('platform')?localStorage.getItem('platform'):'M-site',
        user_type:localStorage.getItem('user_type')
      });
         e.preventDefault();
      window.open("https://finvu.in/terms","_blank");
    }
  
  return (
    <div className='verifyotp'>

{Pendingrequest && <Loader/>}

<div className='mybody'>



<div className='otppanel'>

<div className='inp'>
<p>OTP sent to your registered mobile number</p>


<OtpInput
                containerStyle="otp-input"
                numInputs={6}
                value={otp}
                inputType='number'
                onChange={(value) => {
                    setOtp(value);
                }}
                renderInput={(props,index) => <input inputMode='nummeric' {...props} className={otp && otp[index] ? 'active' : ''}
                autoFocus={index === 0}
                />}
              />

<div className='resend'>
<p  onClick={handleResend} className={time==0?'resend':"re"}>Re-send</p>
{time>0?<p className='time'>In {time} Secs</p>:<></>}
</div>
</div>

<p className='warning'>Please <span>DO NOT</span> switch app while <br></br>reading the <span>OTP</span></p>

<button disabled={otp.length!=6} onClick={handlesubmit}> Verify</button>








</div>

</div>

  )
}```

Clear an input after a search [duplicate]

I need my input to clear after pressing ‘Enter’ to submit a search.
The code I have to submit the search is:

input.addEventListener("keydown", (event) => {
        if (event.key === "Enter"){
        const query = event.target.value;
          displayPhotos(query);} 
        else if (event.key === "Backspace") {
            document.querySelector(".gallery").innerHTML = ''}
        })

So the idea is that when pressing Enter the search is completed and the text should be deleted.
I’ve looked and there are similar questions asked before but I could not find the answer to solve it.

Clear an input after a search

I need my input to clear after pressing ‘Enter’ to submit a search.
The code I have to submit the search is:

input.addEventListener("keydown", (event) => {
        if (event.key === "Enter"){
        const query = event.target.value;
          displayPhotos(query);} 
        else if (event.key === "Backspace") {
            document.querySelector(".gallery").innerHTML = ''}
        })

So the idea is that when pressing Enter the search is completed and the text should be deleted.
I’ve looked and there are similar questions asked before but I could not find the answer to solve it.

I have build an app uisng expo lasted sdk 52.0.37 , now in that app i want have face recognition how can i have?

I am building an app using expo lasted SDK 52.0.37, now in that app I want to have face recognition but what I have found out is Expo FaceDetector is Deprecated now it asked me use react native vision camera but the issue is how can I implementat one as I don’t touch any native code I am using the dev build to test but when I build I get errors in building

any solutions ???