Skip to content

Commit

Permalink
Remove React Router's useNavigate dependency (#1270)
Browse files Browse the repository at this point in the history
**Related Ticket:** Contributes to #1108

This aims to ensure catalog filters work correctly in Next.js.

### Description of Changes

Removes the usage of React Router's `useNavigate` hook in the library to
make it more agnostic of routing frameworks, allowing it to work better
with Next.js instances.

Changes included:

- Added a custom `commit` function to `useQsStateCreator`. It appears
this was the only place where the `useNavigate` function was effectively
in use. I tried using the default `commit` function from the
[qs-state-hook](https://github.com/danielfdsilva/qs-state-hook) library,
but it doesn't work with Next.js
- Formatted the touched files

### Validation / Testing

Using `veda-config`:

1. Visit the data catalog page
2. Click on filters, and URL params are updated as usual
3. Reload the page with filters selected; the filter panel is populated
as expected
4. Repeat the steps on the Exploration and Stories pages

Using `next-veda-ui` instance:

1. Link the source of this PR to the Next.js instance using the
instructions in `veda-ui/docs/development/REGISTRY.md`
2. Replace the file `app/(datasets)/data-catalog/catalog.tsx` (this
avoids build errors caused by type issues)

```js
'use client';
import React from 'react';
import { CatalogView, useFiltersWithQS } from '@lib';
import { usePathname } from 'next/navigation';
import Link from 'next/link';

export default function Catalog({ datasets }: { datasets: any }) {
  const pathname = usePathname();
  const controlVars = useFiltersWithQS();

  return (
    <CatalogView
      datasets={datasets}
      onFilterChanges={() => controlVars}
      pathname={pathname}
      linkProperties={{
        LinkElement: Link,
        pathAttributeKeyName: 'href',
      }}
    />
  );
}
```

3. Access `http://localhost:3000/data-catalog`. Filter changes are
reflected in the URL, and reloading populates the filter panel as
expected

This is ready for review.
  • Loading branch information
vgeorge authored Nov 25, 2024
2 parents 14fc8ea + 34d878f commit edc5d9e
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { FilterActions, FilterAction, onFilterAction } from '../../utils';
export interface UseFiltersWithQueryResult {
search: string;
taxonomies: Record<string, string[]> | Record<string, never>;
onAction: FilterAction
onAction: FilterAction;
}

// @TECH-DEBT: We have diverged ways of dealing with query parameters and need to consolidate them.
Expand All @@ -28,19 +28,26 @@ export function useFiltersWithURLAtom(): UseFiltersWithQueryResult {
return {
search,
taxonomies,
onAction,
onAction
};
}

export function useFiltersWithQS({
navigate
}: {
navigate: any
}): UseFiltersWithQueryResult {

const useQsState = useQsStateCreator({
commit: navigate
});
export function useFiltersWithQS(): UseFiltersWithQueryResult {
const useQsState = useQsStateCreator({
commit: ({ search }) => {
if (typeof window !== 'undefined') {
const currentUrl = new URL(window.location.href);
const searchParams = search.startsWith('?') ? search.slice(1) : search;
currentUrl.search = searchParams;
window.history.pushState({}, '', currentUrl.toString());
} else {
// eslint-disable-next-line no-console
console.log(
'useFiltersWithQS: window is undefined, query string will update.'
);
}
}
});

const [search, setSearch] = useQsState.memo(
{
Expand All @@ -60,16 +67,16 @@ export function useFiltersWithURLAtom(): UseFiltersWithQueryResult {
[]
);


const onAction = useCallback<FilterAction>(
(action, value) => {
onFilterAction(action, value, taxonomies, setSearch, setTaxonomies);},
onFilterAction(action, value, taxonomies, setSearch, setTaxonomies);
},
[setSearch, setTaxonomies, taxonomies]
);

return {
search: search?? '',
taxonomies: taxonomies?? {},
onAction,
search: search ?? '',
taxonomies: taxonomies ?? {},
onAction
};
}
}
17 changes: 11 additions & 6 deletions app/scripts/components/data-catalog/container.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { useNavigate, useLocation } from 'react-router';
import { useLocation } from 'react-router';
import { getString } from 'veda';
import { getAllDatasetsProps } from '$utils/veda-data';
import CatalogView from '$components/common/catalog';
Expand All @@ -21,13 +21,18 @@ import SmartLink from '$components/common/smart-link';
export default function DataCatalogContainer() {
const allDatasets = getAllDatasetsProps(veda_faux_module_datasets);
const pathname = useLocation().pathname;
const navigate = useNavigate();
const controlVars = useFiltersWithQS({navigate: navigate});
const controlVars = useFiltersWithQS();

return (
<PageMainContent>
<LayoutProps title='Data Catalog' description={getString('dataCatalogBanner').other} />
<PageHero title='Data Catalog' description={getString('dataCatalogBanner').other} />
<LayoutProps
title='Data Catalog'
description={getString('dataCatalogBanner').other}
/>
<PageHero
title='Data Catalog'
description={getString('dataCatalogBanner').other}
/>
<FeaturedDatasets />
<CatalogView
datasets={allDatasets}
Expand All @@ -40,4 +45,4 @@ export default function DataCatalogContainer() {
/>
</PageMainContent>
);
}
}
20 changes: 14 additions & 6 deletions app/scripts/components/stories/hub/container.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React from 'react';
import { useNavigate } from 'react-router';

import { stories, getString } from 'veda';
import HubContent from './hub-content';
Expand All @@ -19,10 +18,13 @@ import {

import SmartLink from '$components/common/smart-link';

const allStories = Object.values(stories).map((d) => d!.data).filter(d => !d.isHidden).map((d) => ({ ...d, path: getStoryPath(d)}));
const allStories = Object.values(stories)
.map((d) => d!.data)
.filter((d) => !d.isHidden)
.map((d) => ({ ...d, path: getStoryPath(d) }));

function StoriesHubContainer() {
const controlVars = useFiltersWithQS({navigate: useNavigate()});
const controlVars = useFiltersWithQS();
return (
<PageMainContent>
<LayoutProps
Expand All @@ -40,13 +42,19 @@ function StoriesHubContainer() {
<HubContent
allStories={allStories}
onFilterchanges={() => controlVars}
linkProperties={{ LinkElement: SmartLink, pathAttributeKeyName: 'to'}}
linkProperties={{
LinkElement: SmartLink,
pathAttributeKeyName: 'to'
}}
pathname={STORIES_PATH}
storiesString={{one: getString('stories').one,other: getString('stories').other}}
storiesString={{
one: getString('stories').one,
other: getString('stories').other
}}
/>
</ContentOverride>
</PageMainContent>
);
}

export default StoriesHubContainer;
export default StoriesHubContainer;
8 changes: 6 additions & 2 deletions app/scripts/components/stories/hub/hub-content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ import {
} from '$components/common/fold';
import { useSlidingStickyHeaderProps } from '$components/common/layout-root/useSlidingStickyHeaderProps';
import { Card } from '$components/common/card';
import { CardListGrid, CardMeta, CardTopicsList } from '$components/common/card/styles';
import {
CardListGrid,
CardMeta,
CardTopicsList
} from '$components/common/card/styles';
import EmptyHub from '$components/common/empty-hub';
import { prepareDatasets } from '$components/common/catalog/prepare-datasets';

Expand Down Expand Up @@ -183,7 +187,7 @@ export default function HubContent(props: HubContentProps) {
linkLabel='View more'
linkProperties={{
...linkProperties,
linkTo: `${d.asLink?.url ?? d.path}`,
linkTo: `${d.asLink?.url ?? d.path}`
}}
title={
<TextHighlight value={search} disabled={search.length < 3}>
Expand Down

0 comments on commit edc5d9e

Please sign in to comment.