1

I am having an issue by using js-cookie package in nextjs. I setup store using context api. and my initial state is

const initialState = {
  darkMode: Cookies.get('darkMode') === 'ON' ? true : false,
  cart: {
    cartItems: Cookies.get('cartItems')
      ? JSON.parse(Cookies.get('cartItems'))
      : [],
  },
  userInfo: Cookies.get('userInfo')
    ? JSON.parse(Cookies.get('userInfo'))
    : null,
};

cart and dark mode is working fine but userInfo is undefined. It gave me this error Here is the screenshot

Here is my login.js page code

import React, { useState, useContext, useEffect } from 'react';
import Layout from '../components/Layout/Layout';
import NextLink from 'next/link';
import { useRouter } from 'next/router';
import {
  Typography,
  Button,
  List,
  ListItem,
  TextField,
  Link,
} from '@material-ui/core';
import useStyles from '../utils/style';
import axios from 'axios';
import { Store } from '../utils/store';
import Cookies from 'js-cookie';

const Login = () => {
  const router = useRouter();
  const { redirect } = router.query;
  const { state, dispatch } = useContext(Store);
  const { userInfo } = state;
  useEffect(() => {
    if (userInfo) {
      router.push('/');
    }
  }, []);

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const classes = useStyles();

  const submitHandler = async (e) => {
    e.preventDefault();
    try {
      const { data } = axios.post('/api/users/login', { email, password });
      dispatch({ type: 'USER_LOGIN', payload: data });
      Cookies.set('userInfo', data);
      router.push(redirect || '/');
    } catch (err) {
      alert(err.response.data ? err.response.data.message : err.message);
      console.log(err.message);
    }
  };
  return (
    <Layout title='Login'>
      <form onSubmit={submitHandler} className={classes.form}>
        <Typography component='h1' variant='h1'>
          Login
        </Typography>
        <List>
          <ListItem>
            <TextField
              variant='outlined'
              fullWidth
              id='email'
              label='Email'
              inputProps={{ type: 'email' }}
              onChange={(e) => setEmail(e.target.value)}
            ></TextField>
          </ListItem>
          <ListItem>
            <TextField
              variant='outlined'
              fullWidth
              id='password'
              label='Password'
              inputProps={{ type: 'password' }}
              onChange={(e) => setPassword(e.target.value)}
            ></TextField>
          </ListItem>
          <ListItem>
            <Button variant='contained' type='submit' fullWidth color='primary'>
              Login
            </Button>
          </ListItem>
          <ListItem>
            Do n0t have an account? &nbsp;
            <NextLink href='/register' passHref>
              <Link>Register Here</Link>
            </NextLink>
          </ListItem>
        </List>
      </form>
    </Layout>
  );
};

export default Login;

Kindly help me to resolve this issue. Any help will be appreciated. Thanks

5
  • It seems like Cookies.get('userInfo') doesn't return a string(serialized object). Could you add console.log(Cookies.get('userInfo')) before creating initialState variable ? Commented Nov 23, 2021 at 15:04
  • It is giving undefined Commented Nov 23, 2021 at 15:07
  • This is the reason you get the error. You don't have this specific cookie; therefore, you can't parse it. Commented Nov 23, 2021 at 15:09
  • Although my cart and darkMode is working perfectly. What will be the solution of this. Commented Nov 23, 2021 at 15:10
  • You should debug the area of your code where you set up the cookie. Your POST call to the API is asynchronous and there should be an await before making a request. const { data } = await axios.post('/api/users/login', { email, password }); Also, don't forget to serialize the data before setting it to the cookie. Commented Nov 23, 2021 at 15:19

1 Answer 1

2

When you do Cookies.set in second argument you pass object and it will be save like this [object%20Object], but it must be a string. First you must convert object to string by JSON.stringify() and then set to cookeis.

Cookies.set('userInfo', JSON.stringify(data));
Sign up to request clarification or add additional context in comments.

7 Comments

Recommendation: Always use JSON.parse or JSON.stringify with try/catch block
Its already in try catch block
I have debug all my code but main problem is the js-cookie package. There is something very terrible with this package but i am not getting it
It’s not about package, problem with data which you set to cookies
It was the cached issue. I cleared the cache and now its working perfectly
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.