Compare commits

...

2 Commits

Author SHA1 Message Date
ahmadshaheer
88c3fa8a64 chore: improve comments 2024-10-16 18:43:48 +04:30
ahmadshaheer
0319da35ac fix: fix the race condition resulting in switching between views not working properly 2024-10-16 17:31:19 +04:30

View File

@@ -1,7 +1,8 @@
import useUrlQuery from 'hooks/useUrlQuery';
import { useCallback, useMemo } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import useUrlQuery from './useUrlQuery';
const useUrlQueryData = <T>(
queryKey: string,
defaultData?: T,
@@ -10,7 +11,7 @@ const useUrlQueryData = <T>(
const location = useLocation();
const urlQuery = useUrlQuery();
const query = useMemo(() => urlQuery.get(queryKey), [queryKey, urlQuery]);
const query = useMemo(() => urlQuery.get(queryKey), [urlQuery, queryKey]);
const queryData: T = useMemo(() => (query ? JSON.parse(query) : defaultData), [
query,
@@ -21,11 +22,19 @@ const useUrlQueryData = <T>(
(newQueryData: T): void => {
const newQuery = JSON.stringify(newQueryData);
urlQuery.set(queryKey, newQuery);
const generatedUrl = `${location.pathname}?${urlQuery.toString()}`;
// Create a new URLSearchParams object with the current URL's search params
// This ensures we're working with the most up-to-date URL state
const currentUrlQuery = new URLSearchParams(window.location.search);
// Update or add the specified query parameter with the new serialized data
currentUrlQuery.set(queryKey, newQuery);
// Construct the new URL by combining the current pathname with the updated query string
const generatedUrl = `${location.pathname}?${currentUrlQuery.toString()}`;
history.replace(generatedUrl);
},
[history, location, urlQuery, queryKey],
[history, location.pathname, queryKey],
);
return {