Reputation: 123
Let me explain my problem. I have an app reacting on an RBAC model using Redux. To do this, I need to call my dispatch() in the useEffect when loading my app to check if the user is authenticated or not. If yes, I would need to dispatch its information contained in the jwt token.
So I did something like this (in App.jsx) :
const App = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const dispatch = useDispatch()
const authentication = () =>
isAuthenticated ? (
<Redirect to="/app" />
) : (
<PublicRoutes />
);
useEffect(() => {
setIsAuthenticated(Auth.isAuth())
if(isAuthenticated){
store.dispatch(setConnectedUser({name:"Jude"}))
}
}, [isAuthenticated])
const store = createStore(rootReducer, composeWithDevTools(
applyMiddleware(thunk),
));
return (
<Provider store={store}>
<HashRouter>
<Switch>
<Route path="/app" component={PrivateRoutes} />
<Route path="" render={authentication} />
</Switch>
</HashRouter>
</Provider>
);
}
export default App;
ReactDOM.render(<App />, document.getElementById("root"))
Auth.isAuth() just fetches the token, checks if the token is still valid, and if so it returns true.
But here's the thing, by doing it this way I'm making an error : Uncaught Error: could not find react-redux context value; please ensure the component is wrapped in a
I understand that the mistake comes from the fact that I want to dispatch() outside the provider, but is it possible to do so? or would I do it wrong? This is my first project with Redux, maybe I didn't fully understand how it works?
Knowing that the dispatch() works very well, it was called at login time before, but I have an error on my header that will retrieve the info from the reducer, it tries to display the store information before it is there, that's why I would like to do the control at application loading, and not only at login.
Upvotes: 1
Views: 1069
Reputation: 106
With your code you aren't able to use redux in this component, just in all his children.
You can just set the provider outside, maybe in the index.js (or wherever you do the ReactDOM.render() or any superior call).
Or if you wish, you can create any new element that will be used in App.js, like 'router.js' or similar where you can check your logic and redirect for where you want.
Upvotes: 3