NuxtN
Nuxt15mo ago
19 replies
Paul

useCookie not being reactive

Hello, I'm currently trying to implement login function and I want to store the access token in the cookie. Here's the following setup:

composables/useAuth.ts:
const useAuth = () => {
  const accessToken = useCookie('at');
 
  const login = async () => {
   const data = await $fetch('/auth/login', {
      method: 'post',
      body: param
    })
    accessToken.value =  data.access_token  
  };

  return { login };
};


pages/login.vue:
<script lang="ts" setup>
const {login} = useAuth()

const form = ref({
  email: '',
  password: ''
})

const accessToken = useCookie('at')

const onSubmit = async () => {
  try {
    await login(form.value)
    console.log(accessToken.value) <-- this returns undefined
  } catch (e) {

  }
}
</script>



From the above, when I called accessToken.value after the login method, it's still undefined, although it returns actual token after I refresh the page fully. Why is that? How can I fix it? Thank you!
Was this page helpful?