TypeError: Cannot read properties of undefined (reading 'set')

Issue

While I am trying to develop mern ec site.
This error has occurred on the sign in page.

what I have tried

1 Cookies->Cookie, set->Set

2 res.refresh_token->’res.refresh_token’

3 downgrade js-cookies version from 3 to 2.2.1

enter image description here

Cookies.set('refreshtoken', res.refresh_token, {
      path: 'api/auth/accessToken',
      expires: 7
    })

all code(except html)

import Head from "next/head"
import Link from "next/link"
import { useState, useContext } from "react"
import { DataContext } from "../store/GlobalState"
import { postData } from "../utils/fetchData"
import { Cookies } from 'js-cookie'

const Signin = () => {
  const initialState = { email: '', password: '' }
  const [userData, setUserData] = useState(initialState)
  const { email, password } = userData

  const { state, dispatch } = useContext(DataContext)

  const handleChangeInput = e => {
    const { name, value } = e.target
    setUserData({ ...userData, [name]: value })
    dispatch({ type: 'NOTIFY', payload: {} })
  }

  const handleSubmit = async e => {
    e.preventDefault()
    dispatch({ type: 'NOTIFY', payload: { loading: true } })
    const res = await postData('auth/login', userData)

    if (res.err) return dispatch({ type: 'NOTIFY', payload: { error: res.err } })
    dispatch({ type: 'NOTIFY', payload: { success: res.msg } })

    dispatch({
      type: 'AUTH', payload: {
        token: res.access_token,
        user: res.user
      }
    })

    Cookies.set('refreshtoken', res.refresh_token, {
      path: 'api/auth/accessToken',
      expires: 7
    })

    localStorage.setItem('firstLogin', true)
  }
}

export default Signin

Solution

As per the docs for js-cookie, your import statement is a little off. Try this:

import Cookies from 'js-cookie'

The way you are importing it, it is return undefined as the Cookies object is the default import, and not nested inside the module exports.

Answered By – about14sheep

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published