Reputation: 123
I wanted to use react at my project. But I' m getting error like "useEffect must not return anything besides a function, which is used for clean-up. You returned: [object Object]". How can I navigate user to Home component? Can you give me an idea?
Login/index.js
const Login = (props) => {
const [errors,setErrors] = useState([]);
const [error,setError] = useState(null);
useEffect(() => {
if(props.AuthStore.appState != null){
if(props.AuthStore.appState.isLoggedIn){
return <Navigate to={{pathname:'/'}} />
}
}
},[]);
const _handleSubmit = async(values, {setSubmitting})=>{
await axios.post(`${API_URL}/api/auth/login`, {
...values
}).then(async (result) => {
const userData = {
...result.data
};
const appState = {
isLoggedIn:true,
user:userData
}
await props.AuthStore.save(appState);
window.location.reload();
})
.catch((error)=>{
console.log(error.response);
})
}
PrivateRoute.js
AuthStore.get();
const isLoggedIn = AuthStore.appstate != null && AuthStore.appstate.isLoggedIn;
const PrivateRoute = ({ component: Component }) => {
return isLoggedIn ? <Component /> : <Navigate to={{pathname:'/login'}} /> ;
}
AppRoutes.js
const AppRoutes = (props) => {
useEffect(() => {
props.AuthStore.get()
}, [])
return (
<Suspense fallback={<div>Fallback</div>}>
<Routes>
<Route path="/" element={<PrivateRoute component={Home} />} />
<Route path="/login" element={<Login />} />
<Route path="/profile" element={<Profile />} />
<Route path="/register" element={<Register />} />
<Route path="/support" element={<Support />} />
</Routes>
</Suspense>
);
};
Upvotes: 0
Views: 170
Reputation: 52
You can try useNavigate()
, it will look like this in your case.
import { useNavigate } from "react-router-dom";
const Login = (props) => {
const navigate = useNavigate()
const [errors,setErrors] = useState([]);
const [error,setError] = useState(null);
useEffect(() => {
if(props.AuthStore.appState != null){
if(props.AuthStore.appState.isLoggedIn){
navigate('/')
}
}
},[]);
Upvotes: 1