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 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?
<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
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.