Reputation: 553
I have an app that have different access level, like admin, guest and normal user, so it has several roles. My folder structure is very clear, some components are shared like Button, Loader but reducers and actions are not shared, because they are completely different of apps.
I did this to do conditioning setting for my store (Yes I only need one store because the entry for all type of the user is the same)
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { getUserRole } from './utils' // merely localstorage util to get roles
import { composeWithDevTools } from 'redux-devtools-extension'
import userReducers from './reducers'
import adminReducers from './reducers/admin'
//share reducer btw member and admin
let reducers
if (getUserRole() === 'member') {
reducers = userReducers
} else {
reducers = adminReducers
}
console.log('reducers', reducers) //undefined during the first load, most likely store is done setup before localstorage?
const store = createStore(
reducers,
composeWithDevTools(
applyMiddleware(thunk)
)
)
export default store
The problem is reducers is undefined
unless I refresh the entire page.
Upvotes: 2
Views: 518
Reputation: 4139
Maybe the problem is that localStore
is not async according to this SO answer.
So by returning a Promise
you'll make sure getUserRole()
is not undefined
:
export function getUserRole(){
return new Promise((resolve, reject) => {
let role = localStorage.getItem('token').decode('role')
resolve(role)
})
}
and in index.js
:
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { getUserRole } from './utils' // merely localstorage util to get roles
import { composeWithDevTools } from 'redux-devtools-extension'
import userReducers from './reducers'
import adminReducers from './reducers/admin'
//share reducer btw member and admin
let store
getUserRole().then(role => {
reducers = role === 'member'
? userReducers
: adminReducers
console.log('reducers', reducers)
store = createStore(
reducers,
composeWithDevTools(
applyMiddleware(thunk)
)
)
})
export default store
Tell me if something went wrong.
Upvotes: 1