basir / next-amazona

next-amazona.vercel.app
289 stars 226 forks source link

Unexpected token o in JSON at position 1 #2

Closed IlirBajrami closed 3 years ago

IlirBajrami commented 3 years ago

I'm having the SyntaxError: Unexpected token o in JSON at position 1 when saving the userInfo to Cookie. The Cookie value is [object%Object]

Screenshot 2021-09-01 at 12 34 43

What am i doing wrong?

IlirBajrami commented 3 years ago

i fixed this by adding JSON.stringify to user data like this:

const submitHandler = async (e) => {
    e.preventDefault();
    try {
      const { data } = await axios.post("/api/users/login", {
        email,
        password,
      });
      dispatch({ type: "USER_LOGIN", payload: data });
      Cookies.set("userInfo", JSON.stringify(data)); // <------- JSON.stringify added here
      router.push(redirect || "/");
    } catch (err) {
      alert(err.response.data ? err.response.data.message : err.message);
    }
  };

Is this the right way?

MiladArdehali commented 3 years ago

Yes @IlirBajrami, This is the right solution 👍

IlirBajrami commented 3 years ago

Ok, thanks!

chriswch commented 2 years ago

The same issue is in pages/register.js. JSON.stringify() should be added to user data in Cookies.set().