0

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!

Westsi
  • 142
  • 2
  • 10
  • 6
    You need to use `JSON.stringify(toAppend)` in order to store complex values in local storage. You can only parse valid JSON and you are not storing valid JSON, hence the error. – Mushroomator Apr 20 '22 at 16:54
  • 1
    As @Mushroomator alluded to, `localStorage` can only store strings. to read it back out you need to `JSON.parse(value_from_storage)` – Pellay Apr 20 '22 at 16:56
  • @Mushroomator yes and gre_gor to an extent – Westsi Apr 20 '22 at 17:14

0 Answers0