forked from dagster-io/dagster
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add useQueryAndLocalStoragePersistedState hook for persisting state t…
…o both localStorage and queryStrings (dagster-io#18868) ## Summary & Motivation We want to be able to persist state to both localStorage and queryStrings while relying on the queryString as the source of truth if both localStorage and the query string are present ## How I Tested These Changes I wrote Jest tests + tested in the asset graph that the behavior works as expected.
- Loading branch information
Showing
6 changed files
with
216 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
137 changes: 137 additions & 0 deletions
137
...er-ui/packages/ui-core/src/hooks/__tests__/useQueryAndLocalStoragePersistedState.test.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
import {act, renderHook, waitFor} from '@testing-library/react'; | ||
import React from 'react'; | ||
import {MemoryRouter, Route} from 'react-router-dom'; | ||
|
||
import {useQueryAndLocalStoragePersistedState} from '../useQueryAndLocalStoragePersistedState'; | ||
|
||
// Mock local storage | ||
const localStorageMock = (() => { | ||
let store: Record<string, string> = {}; | ||
|
||
return { | ||
getItem: (key: string) => store[key] || null, | ||
setItem: (key: string, value: string) => { | ||
store[key] = value.toString(); | ||
}, | ||
removeItem: (key: string) => { | ||
delete store[key]; | ||
}, | ||
clear: () => { | ||
store = {}; | ||
}, | ||
}; | ||
})(); | ||
|
||
Object.defineProperty(window, 'localStorage', { | ||
value: localStorageMock, | ||
}); | ||
|
||
describe('useQueryAndLocalStoragePersistedState', () => { | ||
afterEach(() => { | ||
localStorageMock.clear(); | ||
}); | ||
|
||
test('persists state to localStorage and loads initial state from local storage', async () => { | ||
let querySearch: string | undefined; | ||
|
||
const localStorageKey = 'asset-graph-open-nodes'; | ||
|
||
localStorageMock.setItem(localStorageKey, JSON.stringify({'open-nodes': ['test']})); | ||
|
||
const hookResult = renderHook( | ||
() => | ||
useQueryAndLocalStoragePersistedState<Set<string>>({ | ||
localStorageKey: 'asset-graph-open-nodes', | ||
encode: (val) => { | ||
return {'open-nodes': Array.from(val)}; | ||
}, | ||
decode: (qs) => { | ||
return new Set(qs['open-nodes']); | ||
}, | ||
isEmptyState: (val) => val.size === 0, | ||
}), | ||
{ | ||
wrapper: ({children}: {children?: React.ReactNode}) => { | ||
return ( | ||
<MemoryRouter initialEntries={['/foo/hello']}> | ||
{children} | ||
<Route | ||
path="*" | ||
render={({location}) => (querySearch = location.search) && <span />} | ||
/> | ||
</MemoryRouter> | ||
); | ||
}, | ||
}, | ||
); | ||
|
||
let state, setter: any; | ||
|
||
[state, setter] = hookResult.result.current; | ||
|
||
// Assert that the state was retrieved from local storage | ||
expect(localStorageMock.getItem(localStorageKey)).toEqual( | ||
JSON.stringify({'open-nodes': ['test']}), | ||
); | ||
|
||
expect(state).toEqual(new Set(['test'])); | ||
|
||
act(() => { | ||
setter(new Set(['test', 'test2'])); | ||
}); | ||
|
||
[state, setter] = hookResult.result.current; | ||
|
||
expect(localStorageMock.getItem(localStorageKey)).toEqual( | ||
JSON.stringify({'open-nodes': ['test', 'test2']}), | ||
); | ||
|
||
expect(state).toEqual(new Set(['test', 'test2'])); | ||
|
||
await waitFor(() => { | ||
expect(querySearch).toEqual('?open-nodes%5B%5D=test&open-nodes%5B%5D=test2'); | ||
}); | ||
}); | ||
|
||
test('uses queryString as source of truth if query string is present and localStorage data is also present', async () => { | ||
const localStorageKey = 'asset-graph-open-nodes'; | ||
|
||
localStorageMock.setItem(localStorageKey, JSON.stringify({'open-nodes': ['test']})); | ||
|
||
const hookResult = renderHook( | ||
() => | ||
useQueryAndLocalStoragePersistedState<Set<string>>({ | ||
localStorageKey: 'asset-graph-open-nodes', | ||
encode: (val) => { | ||
return {'open-nodes': Array.from(val)}; | ||
}, | ||
decode: (qs) => { | ||
return new Set(qs['open-nodes']); | ||
}, | ||
isEmptyState: (val) => val.size === 0, | ||
}), | ||
{ | ||
wrapper: ({children}: {children?: React.ReactNode}) => { | ||
return ( | ||
<MemoryRouter | ||
initialEntries={[ | ||
'/foo/hello?open-nodes%5B%5D=basic_assets_repository%40toys%3Abasic_assets', | ||
]} | ||
> | ||
{children} | ||
</MemoryRouter> | ||
); | ||
}, | ||
}, | ||
); | ||
|
||
const [state] = hookResult.result.current; | ||
|
||
// Assert that the state was retrieved from local storage | ||
expect(localStorageMock.getItem(localStorageKey)).toEqual( | ||
JSON.stringify({'open-nodes': ['test']}), | ||
); | ||
|
||
expect(state).toEqual(new Set(['basic_assets_repository@toys:basic_assets'])); | ||
}); | ||
}); |
53 changes: 53 additions & 0 deletions
53
js_modules/dagster-ui/packages/ui-core/src/hooks/useQueryAndLocalStoragePersistedState.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import React from 'react'; | ||
|
||
import {QueryPersistedDataType, useQueryPersistedState} from './useQueryPersistedState'; | ||
import {useSetStateUpdateCallback} from './useSetStateUpdateCallback'; | ||
|
||
/** | ||
* | ||
* Use URL query string as main source of truth with localStorage as the backup if no state is found in the query string | ||
* Syncs changes back to localStorage but relies solely on queryString after the initial render | ||
* @returns | ||
*/ | ||
export const useQueryAndLocalStoragePersistedState = <T extends QueryPersistedDataType>( | ||
props: Parameters<typeof useQueryPersistedState<T>>[0] & { | ||
localStorageKey: string; | ||
isEmptyState: (state: T) => boolean; | ||
}, | ||
): [T, (setterOrState: React.SetStateAction<T>) => void] => { | ||
// Grab state from localStorage as "initialState" | ||
const initialState = React.useMemo(() => { | ||
try { | ||
const value = localStorage.getItem(props.localStorageKey); | ||
if (value) { | ||
return props.decode?.(JSON.parse(value)); | ||
} | ||
} catch {} | ||
return undefined; | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, [props.localStorageKey]); | ||
|
||
const [state, setter] = useQueryPersistedState(props); | ||
|
||
const isFirstRender = React.useRef(true); | ||
React.useEffect(() => { | ||
if (initialState && props.isEmptyState(state)) { | ||
setter(initialState); | ||
} | ||
isFirstRender.current = false; | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, []); | ||
|
||
return [ | ||
isFirstRender.current && initialState && props.isEmptyState(state) ? initialState : state, | ||
useSetStateUpdateCallback(state, (nextState) => { | ||
setter(nextState); | ||
|
||
// Persist state updates to localStorage | ||
window.localStorage.setItem( | ||
props.localStorageKey, | ||
JSON.stringify(props.encode ? props.encode(nextState) : nextState), | ||
); | ||
}), | ||
]; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters