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
|
import { useMemo } from 'react'
import {applyMiddleware, compose, createStore} from 'redux'
import { createLogger } from 'redux-logger'
import createSagaMiddleware from 'redux-saga'
import thunk from 'redux-thunk'
import rootReducer from './reducers'
import rootSaga from './sagas'
import { viewportAdjustmentMiddleware } from './middleware/viewport-adjustment'
import { createReduxEnhancer } from "@sentry/react";
let store
function initStore(initialState, ctx) {
const sagaMiddleware = createSagaMiddleware({ context: ctx })
const middlewares = [thunk, sagaMiddleware, viewportAdjustmentMiddleware]
if (process.env.NODE_ENV !== 'production') {
middlewares.push(createLogger())
}
let middleware = applyMiddleware(...middlewares)
if (process.env.NEXT_PUBLIC_SENTRY_DSN) {
middleware = compose(middleware, createReduxEnhancer())
}
const configuredStore = createStore(rootReducer, initialState, middleware)
sagaMiddleware.run(rootSaga)
store = configuredStore
return configuredStore
}
export const initializeStore = (preloadedState, ctx) => {
let _store = store ?? initStore(preloadedState, ctx)
// After navigating to a page with an initial Redux state, merge that state
// with the current state in the store, and create a new store
if (preloadedState && store) {
_store = initStore({
...store.getState(),
...preloadedState,
})
// Reset the current store
store = undefined
}
// For SSG and SSR always create a new store
if (typeof window === 'undefined') return _store
// Create the store once in the client
if (!store) store = _store
return _store
}
export function useStore(initialState, ctx) {
return useMemo(() => initializeStore(initialState, ctx), [initialState, ctx])
}
|