Reputation:
I'm trying to get the UID of the current user in firebase in my root file (App.js) but I encountered a problem regarding react-redux even though I wrapped in Provider and set a store. By the way, I'm using redux-toolkit. What am I missing here? Thanks for the answer.
Below is my App.js
import { StrictMode, useEffect } from 'react'
import { Provider } from 'react-redux';
import { useDispatch } from 'react-redux';
import { getCurrentUser } from 'store/slices/authSlice';
import store from 'store';
import routes from 'routes/routes';
import PrivateRoute from 'routes/PrivateRoutes';
const App = () => {
const dispatch = useDispatch();
useEffect(() => {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user;
console.log(uid);
dispatch(getCurrentUser(uid))
} else {
// User is signed out
// ...
}
});
}, [dispatch]);
return (
<StrictMode>
<Provider store={store}>
<Router>
<Switch>
{routes.map((route, i) => (
route.auth ? (
<PrivateRoute
key={i}
exact
path={route.path}
component={route.component}
/>
) : (
<Route
key={i}
exact
path={route.path}
component={route.component}
/>
)
))}
</Switch>
</Router>
</Provider>
</StrictMode>
);
}
export default App;
Upvotes: 2
Views: 6912
Reputation: 2495
App
must be wrapped in provider since you are using useDispatch
in it. Right now it's just a child. Provider
sets the context so only its children can have access to it, not a parent.
Try:
import { StrictMode, useEffect } from 'react'
import { Provider } from 'react-redux';
import { useDispatch } from 'react-redux';
import { getCurrentUser } from 'store/slices/authSlice';
import store from 'store';
import routes from 'routes/routes';
import PrivateRoute from 'routes/PrivateRoutes';
const AppWrapper = () => {
const store = createStore(rootReducer);
return (
<Provider store={store}> // Set context
<App /> // Now App has access to context
</Provider>
)
}
const App = () => {
const dispatch = useDispatch();
useEffect(() => {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user;
console.log(uid);
dispatch(getCurrentUser(uid))
} else {
// User is signed out
// ...
}
});
}, [dispatch]);
return (
<StrictMode>
<Provider store={store}>
<Router>
<Switch>
{routes.map((route, i) => (
route.auth ? (
<PrivateRoute
key={i}
exact
path={route.path}
component={route.component}
/>
) : (
<Route
key={i}
exact
path={route.path}
component={route.component}
/>
)
))}
</Switch>
</Router>
</Provider>
</StrictMode>
);
}
export default App;
Upvotes: 1
Reputation: 306
The problem is that you are trying to use useDispatch
in your main component, which is not wrapped with a Provider
. You should create a navigator or router component and do it inside that one
Upvotes: 0