login in frontend
This commit is contained in:
parent
cfabd4e7ff
commit
5ac961330e
|
@ -69,3 +69,37 @@ export const postUser = async (content) => {
|
|||
throw new Error('Failed to save user. ' || error.message);
|
||||
}
|
||||
};
|
||||
|
||||
export const loginUser = async (loginValue) => {
|
||||
const protocol = process.env.REACT_APP_API_PROTOCOL; // "http"
|
||||
const host = process.env.REACT_APP_API_HOST; // "localhost"
|
||||
const port = process.env.REACT_APP_API_PORT; // "8080"
|
||||
const path = process.env.REACT_APP_API_PATH; // "/api"
|
||||
const portPart = port ? `:${port}` : ''; // port is optional
|
||||
const API_URL = `${protocol}://${host}${portPart}${path}`;
|
||||
|
||||
try {
|
||||
|
||||
const response = await fetch(`${API_URL}/users/login`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email: `${loginValue.email}`,
|
||||
password: `${loginValue.password}`,
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json;
|
||||
throw new Error(errorData.message || 'Server response failed.');
|
||||
}
|
||||
const data = response;
|
||||
console.log('User successfully logged in:', data);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Failed to log in:', error.message);
|
||||
throw new Error('Failed to log in. ' || error.message);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
import { useNavigate } from 'react-router-dom';
|
||||
import { loginUser } from '../../comunication/FetchUser';
|
||||
|
||||
/**
|
||||
* LoginUser
|
||||
|
@ -9,8 +10,18 @@ function LoginUser({loginValues, setLoginValues}) {
|
|||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
try {
|
||||
let isLoginValid = false
|
||||
isLoginValid = await loginUser(loginValues);
|
||||
console.log(loginValues);
|
||||
navigate('/')
|
||||
if (isLoginValid) {
|
||||
setLoginValues({ userName: loginValues.email, password: loginValues.password });
|
||||
navigate('/');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch to server:', error.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
|
|
Loading…
Reference in New Issue