Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ is one of `'replace' | 'replaceIn' | 'push' | 'pushIn'`, defaulting to
`'replaceIn'`.

You may optionally pass in a rawQuery object, otherwise the query is derived
from the location available in the QueryParamContext.
from the location in the context.

**Example**

Expand Down
18 changes: 18 additions & 0 deletions src/LocationContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import * as React from 'react';
import { EncodedQueryWithNulls } from 'serialize-query-params';

import { UrlUpdateType } from './types';

/**
* Shape of the LocationProviderContext, which the hooks consume to read and
* update the URL state.
*/
type LocationProviderContext = [
Location,
(queryReplacements: EncodedQueryWithNulls, updateType?: UrlUpdateType) => void
];

export const LocationContext = React.createContext<LocationProviderContext>([
{} as Location,
() => {},
]);
50 changes: 50 additions & 0 deletions src/LocationProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import * as React from 'react';
import { EncodedQueryWithNulls } from 'serialize-query-params';

import { UrlUpdateType, HistoryLocation } from './types';
import { updateUrlQuery, getLocation } from './updateUrlQuery';
import { LocationContext } from './LocationContext';

/**
* Props for the LocationProvider.
*/
type LocationProviderProps = HistoryLocation & {
/** Main app goes here */
children: React.ReactNode;
};

/**
* An internal-only context provider which provides down the most
* recent location object and a callback to update the history.
*/
export function LocationProvider({
history,
location,
children,
}: LocationProviderProps) {
const locationRef = React.useRef(location);
React.useEffect(() => {
locationRef.current = location;
}, [location]);

const setContext = React.useCallback(
(queryReplacements: EncodedQueryWithNulls, updateType?: UrlUpdateType) => {
// A ref is needed here to stop setContext updating constantly (see #46)
locationRef.current = getLocation(
queryReplacements,
locationRef.current,
updateType
);
if (history) {
updateUrlQuery(history, locationRef.current, updateType);
}
},
[history]
);

return (
<LocationContext.Provider value={[location, setContext]}>
{children}
</LocationContext.Provider>
);
}
85 changes: 39 additions & 46 deletions src/QueryParamProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,6 @@
import * as React from 'react';
import { PushReplaceHistory } from './types';

/**
* Subset of a @reach/router history object. We only
* care about the navigate function.
*/
interface ReachHistory {
navigate: (
to: string,
options?: {
state?: any;
replace?: boolean;
}
) => void;
}

/**
* Shape of the QueryParamContext, needed to update the URL
* and know its current state.
*/
export interface QueryParamContextValue {
history: PushReplaceHistory;
location: Location;
}
import { HistoryLocation, PushReplaceHistory } from './types';
import { LocationProvider } from './LocationProvider';

/**
* Adapts standard DOM window history to work with our
Expand All @@ -49,6 +27,20 @@ function adaptWindowHistory(history: History): PushReplaceHistory {
};
}

/**
* Subset of a @reach/router history object. We only
* care about the navigate function.
*/
interface ReachHistory {
navigate: (
to: string,
options?: {
state?: any;
replace?: boolean;
}
) => void;
}

/**
* Adapts @reach/router history to work with our
* { replace, push } interface.
Expand Down Expand Up @@ -76,31 +68,32 @@ function adaptReachHistory(history: ReachHistory): PushReplaceHistory {
* Helper to produce the context value falling back to
* window history and location if not provided.
*/
function getContextValue(
contextValue: Partial<QueryParamContextValue> = {}
): QueryParamContextValue {
const value = { ...contextValue };

export function getLocationProps({
history,
location,
}: Partial<HistoryLocation> = {}): HistoryLocation {
const hasWindow = typeof window !== 'undefined';
if (hasWindow) {
if (!value.history) {
value.history = adaptWindowHistory(window.history);
if (!history) {
history = adaptWindowHistory(window.history);
}
if (!value.location) {
value.location = window.location;
if (!location) {
location = window.location;
}
}

return value as QueryParamContextValue;
if (!location) {
throw new Error(`
Could not read the location. Is the router wired up correctly?
`);
}
return { history, location };
}

export const QueryParamContext = React.createContext(getContextValue());

/**
* Props for the Provider component, used to hook the active routing
* system into our controls.
*/
interface Props {
interface QueryParamProviderProps {
/** Main app goes here */
children: React.ReactNode;
/** `Route` from react-router */
Expand All @@ -126,16 +119,16 @@ export function QueryParamProvider({
reachHistory,
history,
location,
}: Props) {
}: QueryParamProviderProps) {
// if we have React Router, use it to get the context value
if (ReactRouterRoute) {
return (
<ReactRouterRoute>
{(routeProps: any) => {
return (
<QueryParamContext.Provider value={getContextValue(routeProps)}>
<LocationProvider {...getLocationProps(routeProps)}>
{children}
</QueryParamContext.Provider>
</LocationProvider>
);
}}
</ReactRouterRoute>
Expand All @@ -145,22 +138,22 @@ export function QueryParamProvider({
// if we are using reach router, use its history
if (reachHistory) {
return (
<QueryParamContext.Provider
value={getContextValue({
<LocationProvider
{...getLocationProps({
history: adaptReachHistory(reachHistory),
location,
})}
>
{children}
</QueryParamContext.Provider>
</LocationProvider>
);
}

// neither reach nor react-router, so allow manual overrides
return (
<QueryParamContext.Provider value={getContextValue({ history, location })}>
<LocationProvider {...getLocationProps({ history, location })}>
{children}
</QueryParamContext.Provider>
</LocationProvider>
);
}

Expand Down
45 changes: 22 additions & 23 deletions src/__tests__/QueryParamProvider-test.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import * as React from 'react';
import { render, cleanup } from '@testing-library/react';
import { QueryParamProvider, QueryParamContext } from '../index';
import { QueryParamProvider } from '../QueryParamProvider';
import { makeMockLocation, makeMockHistory } from './helpers';

// ¯\_(ツ)_/¯
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What should I do with these tests? I wanted to make sure the history-generating code in QueryParamProvider was still working, but I'm no longer passing history down via context.

jest.mock('../LocationProvider', () => ({
LocationProvider: ({ history, children }) => children({ history }),
}));

describe('QueryParamProvider', () => {
afterEach(cleanup);

Expand All @@ -11,13 +16,11 @@ describe('QueryParamProvider', () => {

const tree = (
<QueryParamProvider reachHistory={reachHistory}>
<QueryParamContext.Consumer>
{({ history }) => {
history.replace(makeMockLocation({ foo: '123' }));
history.push(makeMockLocation({ bar: 'zzz' }));
return <div>consumed</div>;
}}
</QueryParamContext.Consumer>
{({ history }) => {
history.replace(makeMockLocation({ foo: '123' }));
history.push(makeMockLocation({ bar: 'zzz' }));
return <div>consumed</div>;
}}
</QueryParamProvider>
);

Expand All @@ -41,13 +44,11 @@ describe('QueryParamProvider', () => {

const tree = (
<QueryParamProvider ReactRouterRoute={MockRoute}>
<QueryParamContext.Consumer>
{({ history }) => {
history.replace(makeMockLocation({ foo: '123' }));
history.push(makeMockLocation({ bar: 'zzz' }));
return <div>consumed</div>;
}}
</QueryParamContext.Consumer>
{({ history }) => {
history.replace(makeMockLocation({ foo: '123' }));
history.push(makeMockLocation({ bar: 'zzz' }));
return <div>consumed</div>;
}}
</QueryParamProvider>
);

Expand All @@ -64,14 +65,12 @@ describe('QueryParamProvider', () => {

const tree = (
<QueryParamProvider>
<QueryParamContext.Consumer>
{({ history }) => {
windowHistory = history;
history.replace(makeMockLocation({ foo: '123' }));
history.push(makeMockLocation({ bar: 'zzz' }));
return <div>consumed</div>;
}}
</QueryParamContext.Consumer>
{({ history }) => {
windowHistory = history;
history.replace(makeMockLocation({ foo: '123' }));
history.push(makeMockLocation({ bar: 'zzz' }));
return <div>consumed</div>;
}}
</QueryParamProvider>
);

Expand Down
Loading