-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.ts
88 lines (78 loc) · 2.28 KB
/
store.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { combineReducers, configureStore } from "@reduxjs/toolkit"
import domainSwapperSlice from "~components/domainSwapperSlice"
import { useDispatch, useSelector } from "react-redux"
import type { TypedUseSelectorHook } from "react-redux"
import { syncStorage } from "redux-persist-webextension-storage"
import {
FLUSH,
PAUSE,
PERSIST,
persistReducer,
persistStore,
PURGE,
REGISTER,
REHYDRATE,
RESYNC
} from "@plasmohq/redux-persist"
import { Storage } from "@plasmohq/storage"
// Here you can add all your reducers
const combinedReducers = combineReducers({
domains: domainSwapperSlice
})
const persistConfig = {
key: "root",
version: 1,
storage: syncStorage
}
// TODO: Fix persistReducer so it doesn't break the types
const persistedReducer = persistReducer(persistConfig, combinedReducers)
// Until persistReducer is fixed, we need to use this mock store to get the types
const mockStore = configureStore({
reducer: combinedReducers
})
// @ts-ignore
export const store = configureStore({
reducer: persistedReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
RESYNC
]
}
})
}) as typeof mockStore
export const persistor = persistStore(store)
// This is what makes Redux sync properly with multiple pages
// Open your extension's options page and popup to see it in action
new Storage().watch({
[`persist:${persistConfig.key}`]: (change) => {
const { oldValue, newValue } = change
const updatedKeys = []
for (const key in oldValue) {
if (oldValue[key] !== newValue?.[key]) {
updatedKeys.push(key)
}
}
for (const key in newValue) {
if (oldValue?.[key] !== newValue[key]) {
updatedKeys.push(key)
}
}
if (updatedKeys.length > 0) {
persistor.resync()
}
}
})
// Get the types from the mock store
export type RootState = ReturnType<typeof mockStore.getState>
export type AppDispatch = typeof mockStore.dispatch
// Export the hooks with the types from the mock store
export const useAppDispatch: () => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector