save progress in local storage
This commit is contained in:
@@ -17,7 +17,6 @@ import { monacoSetup } from 'lean4web/client/src/monacoSetup';
|
||||
|
||||
monacoSetup()
|
||||
|
||||
|
||||
const router = createHashRouter([
|
||||
{
|
||||
path: "/",
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
const KEY = "progress";
|
||||
export function loadState() {
|
||||
try {
|
||||
const serializedState = localStorage.getItem(KEY);
|
||||
if (!serializedState) return undefined;
|
||||
return JSON.parse(serializedState);
|
||||
} catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveState(state: any) {
|
||||
try {
|
||||
const serializedState = JSON.stringify(state);
|
||||
localStorage.setItem(KEY, serializedState);
|
||||
} catch (e) {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createSlice } from '@reduxjs/toolkit'
|
||||
import type { PayloadAction } from '@reduxjs/toolkit'
|
||||
import { loadState } from "./localStorage";
|
||||
|
||||
interface ProgressState {
|
||||
level: {[world: string]: {[level: number]: LevelProgressState}}
|
||||
@@ -10,7 +11,7 @@ interface LevelProgressState {
|
||||
completed: boolean
|
||||
}
|
||||
|
||||
const initialProgressState = { level: {} } as ProgressState
|
||||
const initialProgressState = loadState() ?? { level: {} } as ProgressState
|
||||
const initalLevelProgressState = {code: "", completed: false} as LevelProgressState
|
||||
|
||||
function addLevelProgress(state, action: PayloadAction<{world: string, level: number}>) {
|
||||
|
||||
@@ -3,13 +3,15 @@ import { connection } from '../connection'
|
||||
import thunkMiddleware from 'redux-thunk'
|
||||
import { apiSlice } from './api'
|
||||
import { progressSlice } from './progress'
|
||||
|
||||
import { saveState } from "./localStorage";
|
||||
import { debounce } from "debounce";
|
||||
|
||||
export const store = configureStore({
|
||||
reducer: {
|
||||
[apiSlice.reducerPath]: apiSlice.reducer,
|
||||
[progressSlice.name]: progressSlice.reducer,
|
||||
},
|
||||
// Make connection available in thunks:
|
||||
middleware: getDefaultMiddleware =>
|
||||
getDefaultMiddleware({
|
||||
thunk: {
|
||||
@@ -18,6 +20,15 @@ export const store = configureStore({
|
||||
}).concat(apiSlice.middleware),
|
||||
});
|
||||
|
||||
// Save progress in local storage
|
||||
store.subscribe(
|
||||
// we use debounce to save the state once each 800ms
|
||||
// for better performances in case multiple changes occur in a short time
|
||||
debounce(() => {
|
||||
saveState(store.getState()[progressSlice.name]);
|
||||
}, 800)
|
||||
);
|
||||
|
||||
// Infer the `RootState` and `AppDispatch` types from the store itself
|
||||
export type RootState = ReturnType<typeof store.getState>
|
||||
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
|
||||
|
||||
Reference in New Issue
Block a user