From 6cd30f49798a52792cae026fc7f51ab64b82ce0c Mon Sep 17 00:00:00 2001 From: karishmas6 Date: Fri, 11 Oct 2024 06:17:58 +0530 Subject: [PATCH] fix: infinite loop while auto-submit --- src/components/molecules/UrlForm.tsx | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/components/molecules/UrlForm.tsx b/src/components/molecules/UrlForm.tsx index 9853d64a..8540fab7 100644 --- a/src/components/molecules/UrlForm.tsx +++ b/src/components/molecules/UrlForm.tsx @@ -1,4 +1,4 @@ -import React, { useState, useEffect, useCallback } from 'react'; +import React, { useState, useEffect, useCallback, useRef } from 'react'; import type { SyntheticEvent } from 'react'; import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight'; import { NavBarForm, NavBarInput } from "../atoms/form"; @@ -19,6 +19,7 @@ export const UrlForm = ({ }: Props) => { const [address, setAddress] = useState(currentAddress); const { socket } = useSocketStore(); + const lastSubmittedRef = useRef(''); const onChange = useCallback((event: SyntheticEvent): void => { setAddress((event.target as HTMLInputElement).value); @@ -34,7 +35,8 @@ export const UrlForm = ({ try { // Validate the URL new URL(url); - setCurrentAddress(url); + setCurrentAddress(url); + lastSubmittedRef.current = url; // Update the last submitted URL } catch (e) { alert(`ERROR: ${url} is not a valid url!`); } @@ -45,10 +47,10 @@ export const UrlForm = ({ submitForm(address); }; - // Sync internal state with currentAddress prop when it changes and auto-submit + // Sync internal state with currentAddress prop when it changes and auto-submit once useEffect(() => { setAddress(currentAddress); - if (currentAddress !== '') { + if (currentAddress !== '' && currentAddress !== lastSubmittedRef.current) { submitForm(currentAddress); } }, [currentAddress, submitForm]);