diff --git a/components/Search.tsx b/components/Search.tsx index 1f5097c0d..ea1581a81 100644 --- a/components/Search.tsx +++ b/components/Search.tsx @@ -1,4 +1,4 @@ -import { useRef, useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { useRouter } from 'next/router' import Image from 'next/image' import { OutlinedInput, InputAdornment, styled, InputBaseProps } from '@mui/material' @@ -33,17 +33,32 @@ const StyledInputBase = styled((props: InputBaseProps) => { - const { push, asPath } = useRouter() + const { push, asPath, query } = useRouter() const searchRef = useRef(null) const [showClearBtn, setShowClearBtn] = useState(false) const isHome = asPath === '/' || asPath === '/zh-CN' const theme = useTheme() + useEffect(() => { + if (!searchRef.current) return + if (query.search) { + searchRef.current.value = (query.search as string) || '' + } else { + // on page refresh, next.js's query.search will always be null, so need this fallback + const queryValue = new URLSearchParams(window.location.search).get('search') + if (queryValue) { + searchRef.current.value = queryValue || '' + } + } + if (searchRef.current.value) { + setShowClearBtn(true) + } + }, [query, asPath]) + const handleSearch = async (e: React.KeyboardEvent) => { await handleSearchKeyPress(e, push) if (e.key === 'Enter') { searchRef.current?.blur() - searchRef.current.value = '' setShowClearBtn(false) } } diff --git a/cypress/integration/search/index.spec.ts b/cypress/integration/search/index.spec.ts index d6347a623..d147dd54c 100644 --- a/cypress/integration/search/index.spec.ts +++ b/cypress/integration/search/index.spec.ts @@ -128,7 +128,7 @@ context('Search', () => { cy.get(`${ROOT_SELECTOR} input`).type(UNKNOWN_STRING) cy.get(ROOT_SELECTOR).type('{enter}') cy.url({ timeout: REDIRECT_TIMEOUT }).should('contain', `/tokens/native`) - cy.location('search').should('eq', `?name=${UNKNOWN_STRING}`) + cy.location('search').should('eq', `?name=${UNKNOWN_STRING}&search=${UNKNOWN_STRING}`) }) it('404', () => { diff --git a/utils/handler.ts b/utils/handler.ts index bfbc5bb8c..45894ead9 100644 --- a/utils/handler.ts +++ b/utils/handler.ts @@ -36,7 +36,7 @@ export const handleSearchKeyPress = async (e: React.KeyboardEvent