From 889d89b6ec2fece63ecb07b04fd1a54bbfb73653 Mon Sep 17 00:00:00 2001 From: Oliver Sand Date: Wed, 5 May 2021 11:34:27 +0200 Subject: [PATCH] Fix setting the state with `useQueryParamState` makes inputs lose their focus Signed-off-by: Oliver Sand --- .changeset/short-bobcats-mate.md | 6 ++++++ packages/core/src/hooks/useQueryParamState.ts | 14 +++++++++----- .../ApiExplorerTable/ApiExplorerTable.tsx | 1 - 3 files changed, 15 insertions(+), 6 deletions(-) create mode 100644 .changeset/short-bobcats-mate.md diff --git a/.changeset/short-bobcats-mate.md b/.changeset/short-bobcats-mate.md new file mode 100644 index 0000000000..22aaf11d77 --- /dev/null +++ b/.changeset/short-bobcats-mate.md @@ -0,0 +1,6 @@ +--- +'@backstage/core': patch +'@backstage/plugin-api-docs': patch +--- + +Fix setting the state with `useQueryParamState` makes inputs lose their focus. diff --git a/packages/core/src/hooks/useQueryParamState.ts b/packages/core/src/hooks/useQueryParamState.ts index da303234f5..0a61771eba 100644 --- a/packages/core/src/hooks/useQueryParamState.ts +++ b/packages/core/src/hooks/useQueryParamState.ts @@ -17,7 +17,7 @@ import { isEqual } from 'lodash'; import qs from 'qs'; import { useEffect, useState } from 'react'; -import { useLocation, useNavigate } from 'react-router-dom'; +import { useLocation } from 'react-router-dom'; import { useDebounce } from 'react-use'; function stringify(queryParams: any): string { @@ -58,9 +58,7 @@ type SetQueryParams = (params: T) => void; export function useQueryParamState( stateName: string, - debounceTime: number = 100, ): [T | undefined, SetQueryParams] { - const navigate = useNavigate(); const location = useLocation(); const [queryParamState, setQueryParamState] = useState( extractState(location.search, stateName), @@ -83,10 +81,16 @@ export function useQueryParamState( ); if (location.search !== queryString) { - navigate({ ...location, search: `?${queryString}` }, { replace: true }); + // We fallback to the history API, as navigate from react-router causes + // input elements to loose focus. + history.replaceState( + undefined, + document.title, + `${location.pathname}?${queryString}`, + ); } }, - debounceTime, + 100, [queryParamState], ); diff --git a/plugins/api-docs/src/components/ApiExplorerTable/ApiExplorerTable.tsx b/plugins/api-docs/src/components/ApiExplorerTable/ApiExplorerTable.tsx index 39c2caaf1b..5b9808e26d 100644 --- a/plugins/api-docs/src/components/ApiExplorerTable/ApiExplorerTable.tsx +++ b/plugins/api-docs/src/components/ApiExplorerTable/ApiExplorerTable.tsx @@ -156,7 +156,6 @@ export const ApiExplorerTable = ({ }: ExplorerTableProps) => { const [queryParamState, setQueryParamState] = useQueryParamState( 'apiTable', - 500, ); if (error) {