Skip to content

Commit

Permalink
Merge pull request #90 from MediaComem/store_multiple_projects
Browse files Browse the repository at this point in the history
Manage multiple projects based on url key in store
  • Loading branch information
zweiro authored Dec 2, 2022
2 parents 19f558e + 4186e9c commit ed35207
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
6 changes: 4 additions & 2 deletions src/app/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,24 @@ import browserStorage from "../services/browserStorage";
import recommandationsSlice from "../features/recommandations/recommandationsSlice";
import { isNewImportSvg } from "../features/figma/components/FetchedSVG";

const url = window.location.href;
const key = url.match(/key=([^&]*)/)?.[1] ?? 'empty';
export const store = configureStore({
reducer: {
project: projectReducer,
zonesSlice,
// zonesFigma: zonesFigmaSlice,
recommandations: recommandationsSlice,
},
preloadedState: isNewImportSvg() ? {} : browserStorage.loadState(), // load state from local storage
preloadedState: isNewImportSvg() ? {} : browserStorage.loadState(key), // load state from local storage
});

// Subscribe to the store changes to persist to local storage
store.subscribe(
// we use debounce to save the state once each 500ms
// for better performances in case multiple changes occur in a short time
debounce(() => {
browserStorage.saveState(store.getState());
browserStorage.saveState(store.getState(), key);
}, 500)
);

Expand Down
16 changes: 11 additions & 5 deletions src/services/browserStorage.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
const KEY = 'redux';
const browserStorage = {
loadState: () => {
loadState: (projectKey: string) => {
try {
const serializedState = localStorage.getItem(KEY);
if (!serializedState) return undefined;
return JSON.parse(serializedState);
const projects = JSON.parse(serializedState);
return projects[projectKey];
} catch (e) {
return undefined;
}
},
saveState: (state: any) => {
saveState: (state: any, projectKey: string) => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem(KEY, serializedState);
let bytesimProjects = {} as any;
const serializedState = localStorage.getItem(KEY);
if (serializedState) {
bytesimProjects = JSON.parse(serializedState);
};
bytesimProjects[projectKey] = state;
localStorage.setItem(KEY, JSON.stringify(bytesimProjects));
} catch (e) {
// Ignore
console.error('Failed to save redux store');
Expand Down

0 comments on commit ed35207

Please sign in to comment.