1

I am trying to set/get an array as a cookie in Javascript as follows:

    let features = [];
    
    for(const property in object) {
        ...
        let feature = new Feature(...);

        features.push(feature);
    }

    cookie.set('features', JSON.stringify(features));
    
    console.log(JSON.parse(cookie.get('features')));

and I get the following error: VM21081:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0

P.S. If I do not use stringify/parse the result is undefined.

Could you help me, please?

Thank you in advance.

  • I think the problem is that I'm trying to store objects i.e. new Feature. –  Aug 17 '20 at 06:56
  • before you set the cookie console log features, check this array how it looks like. and if you can share here the result, because it seems like the problem is in the features array – Elna Haim Aug 17 '20 at 07:00
  • yeah, I had checked it and it seems to be filled: (10) [Feature, Feature, Feature, Feature, Feature, Feature, Feature, Feature, Feature, Feature] –  Aug 17 '20 at 07:03
  • Just curious, which library is cookie.set/cookie.get? – Kasalwe Aug 17 '20 at 07:20
  • https://www.npmjs.com/package/js-cookie –  Aug 17 '20 at 07:31
  • I asked because you are using cookie.set (or get) instead of Cookies.set (or get). – Kasalwe Aug 17 '20 at 07:59
  • it depends on how you have defined to use it. I do it as: import * as cookie from 'js-cookie' that's why : ) –  Aug 17 '20 at 08:03
  • Alright. Didn't foresee that one. :) – Kasalwe Aug 17 '20 at 08:19

1 Answers1

0

the issue is that you try to set and get cookies in the browser on the local environment. I copied from the answer in this topic (Why does Chrome ignore local jQuery cookies?)

'Chrome doesn't support cookies for local files (or, like Peter Lyons mentioned, localhost*) unless you start it with the --enable-file-cookies flag. You can read a discussion about it at http://code.google.com/p/chromium/issues/detail?id=535.

*Chrome does support cookies if you use the local IP address (127.0.0.1) directly. so in the localhost case, that could be an easier workaround.'

to test your code you can use w3school editor, here is an example: https://www.w3schools.com/code/tryit.asp?filename=GHTVNK8POVWM

(click run button to see the result)

Elna Haim
  • 545
  • 1
  • 5
  • 19