Skip to content

Commit

Permalink
add redux store persistence
Browse files Browse the repository at this point in the history
implement persistence without using state container or state sync utils, and it
works with both the URL and session storage.

Signed-off-by: abbyhu2000 <abigailhu2000@gmail.com>
  • Loading branch information
abbyhu2000 committed Dec 15, 2022
1 parent bb94a9d commit c73a62e
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

import { VisBuilderServices } from '../../../types';
import { getPreloadedState } from './preload';
import { RootState } from './store';

export const loadReduxState = async (services: VisBuilderServices) => {
try {
const serializedState = services.osdUrlStateStorage.get<RootState>('_a');
if (serializedState === null) {
return await getPreloadedState(services);
}
return serializedState;
} catch (err) {
return await getPreloadedState(services);
}
};

export const saveReduxState = (
{ style, visualization, metadata },
services: VisBuilderServices
) => {
try {
services.osdUrlStateStorage.set<RootState>(
'_a',
{ style, visualization, metadata },
{
replace: true,
}
);
} catch (err) {
return;
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import { reducer as styleReducer } from './style_slice';
import { reducer as visualizationReducer } from './visualization_slice';
import { reducer as metadataReducer } from './metadata_slice';
import { VisBuilderServices } from '../../..';
import { getPreloadedState } from './preload';
import { setEditorState } from './metadata_slice';
import { loadReduxState, saveReduxState } from './redux_persistence';

const rootReducer = combineReducers({
style: styleReducer,
Expand All @@ -25,7 +25,7 @@ export const configurePreloadedStore = (preloadedState: PreloadedState<RootState
};

export const getPreloadedStore = async (services: VisBuilderServices) => {
const preloadedState = await getPreloadedState(services);
const preloadedState = await loadReduxState(services);
const store = configurePreloadedStore(preloadedState);

const { metadata: metadataState, style: styleState, visualization: vizState } = store.getState();
Expand Down Expand Up @@ -62,6 +62,15 @@ export const getPreloadedStore = async (services: VisBuilderServices) => {

previousStore = currentStore;
previousMetadata = currentMetadata;

saveReduxState(
{
style: store.getState().style,
visualization: store.getState().visualization,
metadata: store.getState().metadata,
},
services
);
};

// the store subscriber will automatically detect changes and call handleChange function
Expand Down

0 comments on commit c73a62e

Please sign in to comment.