Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ML] Improvements for urlState hook. #70576

Merged
merged 16 commits into from
Jul 8, 2020
Merged
Changes from 1 commit
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
93 changes: 58 additions & 35 deletions x-pack/plugins/ml/public/application/util/url_state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import { parse, stringify } from 'query-string';
import { useCallback } from 'react';
import { useCallback, useEffect, useState } from 'react';
import { isEqual } from 'lodash';
import { decode, encode } from 'rison-node';
import { useHistory, useLocation } from 'react-router-dom';
Expand Down Expand Up @@ -58,51 +58,74 @@ export function getUrlState(search: string): Dictionary<any> {
// different urlStates(e.g. `_a` / `_g`) don't overwrite each other.
export const useUrlState = (accessor: string): UrlState => {
const history = useHistory();
const { search } = useLocation();
const { search: locationSearch } = useLocation();

// We maintain a local state of useLocation's search.
// This allows us to use the callback variant of setSearch()
// later on so we can make sure we always act on the
// latest url state.
const [search, setSearch] = useState(locationSearch);

useEffect(() => {
setSearch(locationSearch);
}, [locationSearch]);

useEffect(() => {
// Only push to history if something related to the accessor of this
// url state instance is affected (e.g. a change in '_g' should not trigger
// a push in the '_a' instance).
if (!isEqual(getUrlState(locationSearch)[accessor], getUrlState(search)[accessor])) {
Copy link
Contributor

Choose a reason for hiding this comment

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

I'd suggest storing the result of getUrlState in some state value or observable and update it based on URL changes. It will let use to avoid retrieving the value from URL string on each render.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Maybe the naming was just not as obvious, but that PR already does that: locationSearch refers to what we get from React Router's useLocation, search is the state value we keep. getUrlState() is a pure function that just parses the search string so we can compare the namespace/accessor (_g/_a), it's not touching the URL directly.

I pushed some more commits with renames to make this more obvious:

  • renamed getUrlState to parseUrlState
  • renamed locationSearch to locationSearchString
  • renamed search to searchString

Also added a useMemo at the end of the hook so we return a memoized version of the parsed url state.

Copy link
Contributor

Choose a reason for hiding this comment

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

yes, this commit 06b0235 introduced useMemo with a parsed object, this is what I meant 👍

history.push({ search });
}
}, [search]);

const setUrlState = useCallback(
(attribute: string | Dictionary<any>, value?: any) => {
const urlState = getUrlState(search);
const parsedQueryString = parse(search, { sort: false });
setSearch((prevSearch) => {
const urlState = getUrlState(prevSearch);
const parsedQueryString = parse(prevSearch, { sort: false });

if (!Object.prototype.hasOwnProperty.call(urlState, accessor)) {
urlState[accessor] = {};
}

if (typeof attribute === 'string') {
if (isEqual(getNestedProperty(urlState, `${accessor}.${attribute}`), value)) {
return;
if (!Object.prototype.hasOwnProperty.call(urlState, accessor)) {
urlState[accessor] = {};
}

urlState[accessor][attribute] = value;
} else {
const attributes = attribute;
Object.keys(attributes).forEach((a) => {
urlState[accessor][a] = attributes[a];
});
}
if (typeof attribute === 'string') {
if (isEqual(getNestedProperty(urlState, `${accessor}.${attribute}`), value)) {
return prevSearch;
}

try {
const oldLocationSearch = stringify(parsedQueryString, { sort: false, encode: false });
urlState[accessor][attribute] = value;
} else {
const attributes = attribute;
Object.keys(attributes).forEach((a) => {
urlState[accessor][a] = attributes[a];
});
}

Object.keys(urlState).forEach((a) => {
if (isRisonSerializationRequired(a)) {
parsedQueryString[a] = encode(urlState[a]);
} else {
parsedQueryString[a] = urlState[a];
}
});
const newLocationSearch = stringify(parsedQueryString, { sort: false, encode: false });
try {
const oldLocationSearch = stringify(parsedQueryString, { sort: false, encode: false });

if (oldLocationSearch !== newLocationSearch) {
history.push({
search: stringify(parsedQueryString, { sort: false }),
Object.keys(urlState).forEach((a) => {
if (isRisonSerializationRequired(a)) {
parsedQueryString[a] = encode(urlState[a]);
} else {
parsedQueryString[a] = urlState[a];
}
});
const newLocationSearch = stringify(parsedQueryString, { sort: false, encode: false });

if (oldLocationSearch !== newLocationSearch) {
return stringify(parsedQueryString, { sort: false });
}
} catch (error) {
// eslint-disable-next-line no-console
console.error('Could not save url state', error);
}
} catch (error) {
// eslint-disable-next-line no-console
console.error('Could not save url state', error);
}

// as a fallback and to satisfy the hooks callback requirements
// return the previous state if we didn't need or were not able to update.
return prevSearch;
});
},
[search]
);
Expand Down