Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
5
rated 0 times [  11] [ 6]  / answers: 1 / hits: 66520  / 3 Years ago, mon, march 22, 2021, 12:00:00

im using react router v6 and i every time i use initializing for authentication in my main file it shows this error. i cant find a solution in the internet for it. i want to render some routes only when there is a user but now it doesnt render anything.


AuthNavigator



import React, { useState, useEffect } from 'react';
import app from './firebase';
import { Router, Routes, Route } from 'react-router-dom';

import AuthStack from './stacks/AuthStack';
import AppStack from './stacks/AppStack';
import StaticStack from './stacks/StaticStack';

function AuthNavigator() {
const [initializing, setInitializing] = useState(true);
const [user, setUser] = useState(() => app.auth().currentUser);

useEffect(() => {
const unsubscribe = app.auth().onAuthStateChanged((user) => {
if (user) {
setUser(user);
} else {
setUser(null);
}
if (initializing) {
setInitializing(false);
}
});

// cleanup subscription
return unsubscribe;
}, []);

if (initializing) return 'Loading....';

return (
<Router>
<Routes>
<Route path=* element={<StaticStack />} />
<Route path=auth/* element={<AuthStack user={user} />} />
<Route path=app/* element={<AppStack user={user} />} />
</Routes>
</Router>
);
}
export default AuthNavigator;




App.js




import React from 'react';
import './App.css';
import AuthNavigator from './AuthNavigator';
import { Router } from 'react-router-dom';

function App() {
return (
<Router>
<AuthNavigator />
</Router>
);
}

export default App;




More From » reactjs

 Answers
6

I had the same issue. My issue is because of the following reason.
I had a Header component which consists of NavLink which is a router component. I placed this Header component inside the App component. My App component was like this:


function App() {
return(
<Header/>
<Router>
<Routes>
<Route path="/" element={<Homepage/>}/>
<Route path="/shop" element={<Shop/>}/>
<Route path="/signin" element={<Signin/>}/>
</Routes>
</Router>
)
}

In the above App component, I have placed Header component outside of Router. Since in the Header component I have used NavLink which is a Router component caused this error. Then I moved Header component into the Router component then it worked fine. Finally my code looked like this:


function App() {
return(
<Router>
<Header/>
<Routes>
<Route path="/" element={<Homepage/>}/>
<Route path="/shop" element={<Shop/>}/>
<Route path="/signin" element={<Signin/>}/>
</Routes>
</Router>
)
}

[#50342] Thursday, March 4, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianod

Total Points: 667
Total Questions: 106
Total Answers: 92

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
;