I have a login page in react that has a handleSubmit function which looks like this:
const handleSubmit = async e => {
e.preventDefault();
console.log(email, password);
const user = {email, password};
const response = await axios.get('http://localhost:5000/users');
let userExists = false;
console.log(response);
for (let i = 0; i < response.data.length; i++) {
console.log(response.data[i].email);
console.log(response.data[i].password);
if (response.data[i].email == email && response.data[i].password == password) {
userExists = true;
if (userExists) {
const toAppend = [response.data[i].email, response.data[i].password];
console.log(toAppend);
localStorage.setItem('user', toAppend);
navigate('/');
break;
};
};
};
if (userExists === false) {
alert("User does not exist! Did you enter the login data correctly?");
}
};
useEffect(() => {
const loggedInUser = localStorage.getItem("user");
if (loggedInUser) {
const foundUser = JSON.parse(loggedInUser);
setUser(foundUser);
}
}, []);
It gets stored in localStorage and is Key: user, Value:test@test.com,test. However, when I try to access the page again, it should redirect to the homepage ('/'). Instead, I get an error
react-dom.development.js:22670 Uncaught SyntaxError: Unexpected token e in JSON at position 1
at JSON.parse (<anonymous>)
at Login.js:43:1
at commitHookEffectListMount (react-dom.development.js:22969:1)
at commitPassiveMountOnFiber (react-dom.development.js:24702:1)
at commitPassiveMountEffects_complete (react-dom.development.js:24666:1)
at commitPassiveMountEffects_begin (react-dom.development.js:24653:1)
at commitPassiveMountEffects (react-dom.development.js:24641:1)
at flushPassiveEffectsImpl (react-dom.development.js:26848:1)
at flushPassiveEffects (react-dom.development.js:26801:1)
at react-dom.development.js:26597:1
I can only assume that I am not storing my data correctly. The response the server returns looks like this when console logged:
{data: Array(2), status: 200, statusText: 'OK', headers: {…}, config: {…}, …}
config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
data: (2) [{…}, {…}]
headers: {content-length: '288', content-type: 'application/json'}
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: "OK"
[[Prototype]]: Object
I have made the server and it returns
[
{
"email": "test@test.com",
"name": "test",
"about": null,
"password": "test",
"user_id": 1
},
{
"email": "test@test.co",
"name": "test",
"about": null,
"password": "test",
"user_id": 2
}
]
when accessed in a browser. I followed this page on how to make this login system. https://www.freecodecamp.org/news/how-to-persist-a-logged-in-user-in-react/ How can I fix this issue? Thanks!