Search code examples
reactjscookiesgettypeerroruniversal

reactjs universal-cookie package error when calling get()


I have the following two components. They are in separate .js files.

import Cookie from 'universal-cookie'
class Comp1{

   someFunction(){
      // Call google Oauth
      // get userinfo from Oauth response and set the token below
      var cookie = New Cookie();
      cookies.set('user', user, { path: '/' })
      this.props.history.push('/Comp2')
      window.location.reload()
   }

}

---------------------------------------------------------

import cookie from 'universal-cookie'
class Comp2{

   anotherFunction(){
       var user = cookie.get('user');
   }

}

The second component throws the following error:

TypeError: universal_cookie__WEBPACK_IMPORTED_MODULE_4__.default.get is not a function

How do I resolve it?

UPDATE: google oauth flow


Solution

  • Firstly, var cookie = New Cookie(); will cause syntax errors.

    Use var cookie = new Cookie(); as JavaScript keywords as key sensitive.

    Secondly, you are inconsistent with your case-sensitivity again with your imports:

    import Cookie from 'universal-cookie'

    import cookie from 'universal-cookie'

    These will cause confusion. Your going to want to refactor that to standardize across the components. Example just opt with the capital 'C':

    import Cookie from 'universal-cookie'
    

    Lastly, taking into consideration the case-sensitivity I have mentioned & as others have mentioned, you need to instantiate Cookie as it is a class. Here is how your components should look like:

    import Cookie from 'universal-cookie';
    
    class Comp extends React.Component {
      ...
      someFunction() {
        var cookie = new Cookie();
        cookie.set('user', "somecookie", { path: '/' })
      }
      ...
    }
    

    import Cookie from 'universal-cookie'
    
    class Comp extends React.Component {
        ...
        someFunction() {
            var cookie = new Cookie();
            console.log(cookie.get('user'));
        }
        ...
    }
    

    CodeSandBox: https://codesandbox.io/s/universal-cookie-react-components-8lc3m

    Also, just FYI don't use Incognito for testing my sandbox

    enter image description here