I'm successfully setting the cookie and when I do console.log(getCookie('key'))
I see this:
[{"pic":"https://something.jpg","des":"something","price":"something","score":"something","id":0,"explink":"something"}]
But when I run JSON.parse(getCookie('key'))
I get this error:
SyntaxError: Unexpected token u in JSON at position 0
I was trying to use this:
import Layout from '../components/layout';
import { useState, createContext, useEffect } from 'react';
import AppContext from '../components/AppContext';
import '../styles/globals.css';
import { getCookies, getCookie, setCookie, deleteCookie } from 'cookies-next';
export default function MyApp({ Component, pageProps }) {
const [count, setcount] = useState(0);
const [card, setcard] = useState([]);
setCookie('key', JSON.stringify(card));
setcard(JSON.parse(getCookie('key')));
return (
<div>
<AppContext.Provider
value={{
count,
setcount,
card,
setcard,
}}
>
<Layout>
<Component {...pageProps} />
</Layout>
</AppContext.Provider>
</div>
);
}
Why am I getting this error?
I also tried setcard(getCookie('key'));
but I got this error:
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
This error happened while generating the page. Any console logs will be displayed in the terminal window.
CodePudding user response:
getCookie('key')
already parsed. So, you got this error. Try this:
setcard(getCookie('key'))
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
I think you need to setcard
inside useEffect
hook.
useEffect(() => {
setcard(getCookie('key'))
}, [])