when i try access dashboard by lnik (http://localhost:3001/dashboard) in browser it's navigate me back to /signin as it should, but if I logging by correct user it doesn't change route to /dashboard. Connection with "serwer" is working properly, but route stays in /signin. It's early stage so server is only working for one user as yet. I would like someone to point out my mistake.
There is discussed part of main App:(all libraries are correctly imported)
useEffect (() => {
fetch('http://localhost:3000')
.then((response) => response.json())
.then(console.log)})
const [user,setUser] = useState(false);
const isUserValid=(user)=>{
setUser(user);
}
return(
<Routes>
<Route path="/signin" element={<Signin userValue={isUserValid}/>}/>
<Route path="/register" element={<Register />} />
<Route path="/dashboard" element={<PrivateRoute userValid={user}/>}>
<Route element={<Dashboard />} path="/dashboard"/>
</Route>
</Routes>
)
Server (nodejs with express.json and cors):
app.post('/signin', (req, res) => {
if(req.body.email === database.users[0].email &&
req.body.password === database.users[0].password){
res.json('success');
} else {
res.status(400).json('error');
}})
Private Route module:
const PrivateRoute =({children, userValid})=>{
return userValid ? children: <Navigate to="/signin" />;
}
export default PrivateRoute;
Sign in module (form working properly, gets values from inputs and sends to server then gets response):
const Signin =({userValue})=> {
const [userEmail,setUserEmail] = useState('');
const [userPassword,setUserPassword] = useState('');
const onEmailChange = (event) => {
setUserEmail(event.target.value);
}
const onPasswordChange = (event) => {
setUserPassword(event.target.value);
}
const onSubmitSignIn = () => {
fetch('http://localhost:3000/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: userEmail,
password: userPassword
})
})
.then(response => response.json())
.then(data => {
if(data === 'success'){
userValue(true);
window.location.href = "/dashboard";
}
})
}